Java file read and write operation specifies encoding method to prevent garbled characters

Source: Internet
Author: User

Read file: BufferedReader

Reads text from the character input stream, buffering individual characters, providing efficient reading of characters, arrays, and rows.

You can specify the size of the buffer, or you can use the default size. In most cases, the default value is large enough.

Typically, every read request made by reader results in a corresponding read request to the underlying character or byte stream. Therefore, it is recommended to use BufferedReader to wrap all of their read () operations with potentially expensive Reader (such as FileReader and InputStreamReader). For example

BufferedReader in
= new BufferedReader (New FileReader ("foo.in"));
The input for the specified file is buffered. Without buffering, each call to read () or readLine () causes the bytes to be read from the file and returned after it is converted to characters, which is extremely inefficient.
You can localize a program that uses DataInputStream to input by source, by replacing each datainputstream with the appropriate bufferedreader.

To specify how the file is encoded, enter the following modifications:
BufferedReader in = new BufferedReader (new FileReader (Savefilename));
BufferedReader in = new BufferedReader (new InputStreamReader (New FileInputStream (Savefilename), "GB2312"));


Writing files: BufferedWriter

Writes text to the character output stream, buffering individual characters, providing efficient writes of individual characters, arrays, and strings.

You can specify the size of the buffer, or accept the default size. In most cases, the default value is large enough.

The class provides the NewLine () method, which uses the platform's own concept of row delimiters, which is defined by the system Properties Line.separator. Not all platforms use New line characters (' \ n ') to terminate each row. Therefore calling this method to terminate each output line is preferable to writing a new line character directly.

Normally Writer sends its output immediately to the underlying character or byte stream. Unless prompted for output, it is recommended to use BufferedWriter to wrap any Writer whose write () operation might be expensive, such as Filewriters and Outputstreamwriters. For example

PrintWriter out
= new PrintWriter (new BufferedWriter (New FileWriter ("Foo.out"));
The buffer printwriter the output of the file. Without buffering, each call to the print () method causes the character to be converted to bytes and then immediately written to the file, which is extremely inefficient.


In order to specify how the file is encoded:
PrintWriter out = new PrintWriter (new BufferedWriter (New OutputStreamWriter (FileOutputStream), " GB2312 ")));

======================= code Example =======================

Read the file:

[Java]View PlainCopy print?
  1. /**
  2. * Read File contents
  3. *
  4. * @param filepathandname
  5. * String such as c:\\1.txt absolute path
  6. * @return Boolean
  7. */
  8. Public static String ReadFile (String filepathandname) {
  9. String filecontent = "";
  10. try {
  11. File F = new file (Filepathandname);
  12. if (F.isfile () &&f.exists ()) {
  13. InputStreamReader Read = new InputStreamReader (new FileInputStream (f),"UTF-8");
  14. BufferedReader reader=New BufferedReader (read);
  15. String Line;
  16. While (line = Reader.readline ()) = null) {
  17. Filecontent + = line;
  18. }
  19. Read.close ();
  20. }
  21. } catch (Exception e) {
  22. SYSTEM.OUT.PRINTLN ("Error reading file contents operation");
  23. E.printstacktrace ();
  24. }
  25. return filecontent;
  26. }

Write file:

[Java]View PlainCopyprint?
    1. /**
    2. * Write file
    3. *
    4. * @param filepathandname
    5. * String such as c:\\1.txt absolute path
    6. */
    7. Public static void WriteFile (String filepathandname, String filecontent) {
    8. try {
    9. File F = new file (Filepathandname);
    10. if (!f.exists ()) {
    11. F.createnewfile ();
    12. }
    13. OutputStreamWriter write = new OutputStreamWriter (new FileOutputStream (f),"UTF-8");
    14. BufferedWriter writer=New BufferedWriter (write);
    15. Writer.write (filecontent);
    16. Writer.close ();
    17. } catch (Exception e) {
    18. SYSTEM.OUT.PRINTLN ("Error writing file contents operation");
    19. E.printstacktrace ();
    20. }
    21. }

Java file read and write operation specifies encoding method to prevent garbled characters

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.