Several points of note for Java IO stream to read and write files

Source: Internet
Author: User

Usually write IO related code opportunity is very few, but all know use bufferedxxxx to read and write high efficiency, did not expect there are so many traps, these two days suddenly was one of the traps toss a bit: read a file, and then write to another file, before and after two files incredibly different?

After solving this problem, several points of attention are summed up.

Note one: reader/writer read and write binary files are problematic :

 Public voidCopyFile1 () {File srcfile=NewFile ("E://atest//atest.txt"); File Dstfile=NewFile ("E://btest//btest.txt"); BufferedReader in=NULL; BufferedWriter out=NULL; Try{ in=NewBufferedReader (NewFileReader (srcfile)); out=NewBufferedWriter (NewFileWriter (dstfile)); String Line=NULL;  while(line = In.readline ())! =NULL) {Out.write ( line+ "/r/n"); }        }Catch(Exception e) {//Todo:handle ExceptionE.printstacktrace (); }finally {            if(In! =NULL) {                Try{in.close (); }Catch(Exception e) {//Todo:handle ExceptionE.printstacktrace (); }            }                        if(Out! =NULL) {                Try{out.close (); }Catch(Exception e) {//Todo:handle ExceptionE.printstacktrace (); }            }        }

The code above uses BufferedReader to read a file one line at a line, and then uses BufferedWriter to write the read data to another file. If the file is in asccii form, the content will still be read correctly. However, if the file is binary, then the read-write file and read-write before and after the very big difference. Of course, replacing the above ReadLine () with read (char[]) still fails to read and write the binary files correctly. Read and write the binary file, then look at the following note.

Note that offset in read (byte[] b, int offset, int length) does not refer to the full file's full text, but rather the offset of byte array b

It is now known that using Reader/writer cannot read the binary correctly, because Reader/writer is a character stream, and then it is used instead of the byte flow Bufferedinputstream/bufferedoutputstream, The online search example is probably this:

 Public voidCopyFile () {File srcfile=NewFile ("E://atest//atest.gif"); File Dstfile=NewFile ("E://atest//btest.gif"); Bufferedinputstream in=NULL; Bufferedoutputstream out=NULL; Try{ in=NewBufferedinputstream (NewFileInputStream (srcfile)); out=NewBufferedoutputstream (NewFileOutputStream (dstfile)); byte[] B =New byte[1024];  while(In.read (b)! =-1) {out.write (b); }        }Catch(Exception e) {//Todo:handle ExceptionE.printstacktrace (); }finally {            if(In! =NULL) {                Try{in.close (); }Catch(Exception e) {//Todo:handle ExceptionE.printstacktrace (); }            }            if(Out! =NULL) {                Try{out.close (); }Catch(Exception e) {//Todo:handle ExceptionE.printstacktrace (); }            }        }    }

Read 1024 bytes at a time, and then write 1024 bytes. This may seem quite right, but the actual file is different from the original. This is suspected to be read-write not connected, so the code is changed to the following form:

byte New byte [1024x768];             int offset = 0;             int length =-1;              while (length = In.read (b, offset, 1024x768))! =-1) {                out.write (b, offset, length);                 + = length;            }

This is mistaken: read a paragraph first, write a paragraph, then change the offset, and then use the new offset to read a paragraph, write a paragraph, until the file read and write finished. But this is wrong, because after using BUFFEREDXXX, the process has been implemented. The offset in read (byte[] b, int offset, int length) actually refers to when the data is read into array b, where the data is placed from where (i.e., offset) of the array; write (byte[] b, int Offset, int length) is the data in B, from where (offset) to start writing to the file.

Note three: when reading data using length= read (b, 0, 1024), write (b, 0, length) should be used

The first piece of code in the second note, though, is more common on the web, but problematic. What's the problem? The answer is: The problem is on the byte[] B array. Because binary files use the diff tool, they only know the difference, but don't know what is different (is there a more advanced comparison tool?). )。 How to determine its difference? The method is simple: you can see the result by changing the binary file to a text file (Reader/writer this character stream cannot read and write the binary file correctly, but inputstream/outputstream these byte streams can read and write the binary files correctly, can also read and write text files correctly). As a result of the use of 1K (1024 bytes) per read, you will see the results are: After the file after writing a paragraph, the length of the paragraph is the original file size and the size of the B array. In order to further determine what the relationship, read the contents of the file is changed to "1234567890123", and the size of the B array to 10 bytes, then the result is out: write the contents of the file into "12345678901234567890", is read two times. The source 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 read two times, read the first 10 bytes, at this time the element in the B array is the first 10 characters, and then the second time, because the readable content is only 3 characters, The contents of the B-array are changed only by the first 3 characters, and the last 7 characters remain in the previous read. So directly in the form of write (b), the second time the file is written, the content is more than a second read to the content.

The following is the correct read and write (that is, how much content is read, how much content is written, not the entire array):

 Public voidCopyFile () {File srcfile=NewFile ("E://atest//atest.txt"); File Dstfile=NewFile ("E://btest//btest.txt"); Bufferedinputstream in=NULL; Bufferedoutputstream out=NULL; Try{ in=NewBufferedinputstream (NewFileInputStream (srcfile)); out=NewBufferedoutputstream (NewFileOutputStream (dstfile)); intLen =-1; byte[] B =New byte[10];  while(len = In.read (b))! =-1) {Out.write (b,0, Len); }        }Catch(Exception e) {//Todo:handle ExceptionE.printstacktrace (); }finally {            if(In! =NULL) {                Try{in.close (); }Catch(Exception e) {//Todo:handle ExceptionE.printstacktrace (); }            }            if(Out! =NULL) {                Try{out.close (); }Catch(Exception e) {//Todo:handle ExceptionE.printstacktrace (); }            }        }    }

Note the point four: Flush () and close ()

Flush () is the contents of the write buffer all "spit" to the file, if not, it is possible that a lot of content is still in the write buffer, not in the file, that is, there is a loss of possible.

Flush () is called in close (). It is a real sign of file completion, the file content after the completion of the file stream does not close, will lead to some "weird" problems. This flow in the network can be more manifest.

Therefore, after writing the file, pay attention to closing the file read/write stream.

This article transferred from: http://blog.csdn.net/swingline/article/details/5656979/

Several points of note for Java IO stream to read and write files

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.