Notes for reading and writing Java IO streams

Source: Internet
Author: User

Notes for reading and writing Java IO streams
Zookeeper has few opportunities to write IO-related code at ordinary times, but he knows that BufferedXXXX is highly efficient in reading and writing. I didn't expect there are so many traps in it. These two days, I was suddenly tossed by one of the traps: read a file and write it to another file. Are the two files different?

After solving this problem, I summarized several points of attention.


Note: Reader/Writer is faulty in reading/writing binary files.:


Public void copyFile1 () {File srcFile = new File ("E: // atest // atest.txt ");
  • File dstFile = new File ("E: // btest // btest.txt"); BufferedReader in = null;
  • BufferedWriter out = null; try {
  • In = new BufferedReader (new FileReader (srcFile); out = new BufferedWriter (new FileWriter (dstFile ));
  • String line = null;
  • While (line = in. readLine ())! = Null) {out. write (line + "/r/n ");
  • } Catch (Exception e ){
  • // TODO: handle exception e. printStackTrace ();
  • } Finally {if (in! = Null ){
  • Try {in. close ();
  • } Catch (Exception e) {// TODO: handle exception
  • E. printStackTrace ();}
  • }
  • If (out! = Null) {try {
  • Out. close ();} catch (Exception e ){
  • // TODO: handle exception e. printStackTrace ();
  • }}
  • }

    The code above uses BufferedReader to read a file one by one row, and then uses BufferedWriter to write the data read to another file. If the file is in the ASCCII format, the content can still be read correctly. However, if the file is binary, the file after reading and writing is very different from the file before reading and writing. Of course, changing the preceding readLine () to read (char []) still cannot read or write binary files correctly. Read and Write binary files.

    Note: offset in read (byte [] B, int offset, int length) is not the full text of the entire file, but the offset of byte array B.

    We already know that using Reader/Writer cannot read binary files correctly. This is because Reader/Writer is a bytes stream, so we can use the byte stream ufferedInputStream/BufferedOutputStream. The search examples on the Internet are like this:

    Public void copyFile () {File srcFile = new File ("E: // atest // atest.gif ");
  • File dstFile = new File ("E: // atest // btest.gif"); BufferedInputStream in = null;
  • BufferedOutputStream out = null; try {
  • In = new BufferedInputStream (new FileInputStream (srcFile); out = new BufferedOutputStream (new FileOutputStream (dstFile ));
  • Byte [] B = new byte [1024];
  • While (in. read (B )! =-1) {out. write (B );
  • } Catch (Exception e ){
  • // TODO: handle exception e. printStackTrace ();
  • } Finally {if (in! = Null ){
  • Try {in. close ();
  • } Catch (Exception e) {// TODO: handle exception
  • E. printStackTrace ();}
  • } If (out! = Null ){
  • Try {out. close ();
  • } Catch (Exception e) {// TODO: handle exception
  • E. printStackTrace ();}
  • }}
  • }

    Read 1024 bytes each time, and then write 1024 bytes. This seems correct, but the actually written file is different from the original file. In this case, it is suspected that the read and write operations are not connected, so the code is changed to the following form:

    Byte [] B = new byte [1024]; int offset = 0;
  • Int length =-1; while (length = in. read (B, offset, 1024 ))! =-1 ){
  • Out. write (B, offset, length); offset + = length;
  • }

    This is a mistake: first read a paragraph, write a paragraph, then change the offset, and then use the new offset to read and write a paragraph until the file has been read and written. But this is wrong, because BufferedXXX has already implemented this process. The offset in read (byte [] B, int offset, int length) actually refers to the position (I .e. offset) from the array when the read data is saved to array B) similarly, write (byte [] B, int offset, int length) writes data from B to the file.

    NOTE 3: UseLength =Read(B, 0, 1024) when reading data, you should use write (B, 0, length) to write

    The first part of the code in the second note is common on the Internet but problematic. Where is the problem? The answer is: the problem lies in the byte [] B array. Because binary files use comparison tools, they only know the differences, but cannot know the differences (is there a more advanced comparison tool ?). How can we determine its differences? The method is very simple: you can see the result by changing the binary file to a text file (although the Reader/Writer cannot read and write the binary file correctly, however, InputStream/OutputStream can read and write binary files and text files correctly ). Because the 1 K (1024 bytes) reading method is used each time, the result is that there is an extra section after the written file, the length of this segment is related to the size of the original file and the size of array B. To further determine the relationship, change the Read File Content to "1234567890123", and change the size of array B to 10 bytes. Then the result is displayed: the written file is changed to "12345678901234567890", that is, it is read twice. The root cause of the extra content is here: the size of the B array is 10 bytes, and the length of the content to be read is 13 bytes. Then, you need to read the first 10 bytes twice, at this time, the elements in array B are the first 10 characters. When you read the second time, the content of array B is changed only because the readable content contains three characters, the last seven characters are retained. Therefore, the write (B) method is used directly. When a file is written for the second time, the content will write more content that is not read for the second time.

    The following is the correct read/write (that is, the number of content read each time and the number of content written, rather than the entire array ):

    Public void copyFile () {File srcFile = new File ("E: // atest // atest.txt ");
  • File dstFile = new File ("E: // btest // btest.txt"); BufferedInputStream in = null;
  • BufferedOutputStream out = null; try {
  • In = new BufferedInputStream (new FileInputStream (srcFile); out = new BufferedOutputStream (new FileOutputStream (dstFile ));
  • Int len =-1;
  • Byte [] B = new byte [10]; while (len = in. read (B ))! =-1 ){
  • Out. write (B, 0, len );}
  • } Catch (Exception e) {// TODO: handle exception
  • E. printStackTrace ();} finally {
  • If (in! = Null) {try {
  • In. close ();} catch (Exception e ){
  • // TODO: handle exception e. printStackTrace ();
  • }}
  • If (out! = Null) {try {
  • Out. close ();} catch (Exception e ){
  • // TODO: handle exception e. printStackTrace ();
  • }}
  • }}

    Note 4: flush () and close ()

    Flush () refers to all the content in the write buffer to the file. Without it, a lot of content may still exist in the write buffer, rather than in the file, that is, there is a possibility of loss.

    Flush () is called in close (). It is a sign of the true completion of a file. If the file stream is not closed after the file content is written, it may cause some "weird" problems. This is more evident in the network stream.

    Therefore, after writing a file, close the file read/write stream.



  • 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.