A few points of attention in Java IO stream reading and writing files __java

Source: Internet
Author: User
Tags readline

Usually write IO-related code opportunities are very few, but all know the use of bufferedxxxx to read and write efficient, did not expect that there are so many traps, these two days suddenly be one of the traps toss about: read a file, and then write to another file, before and after two files incredibly different.

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

Note: reader/writer read and write binaries are problematic :

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 reads a file one line at a bufferedreader and then writes the read data to another file using BufferedWriter. If the file is in asccii form, the content can be read correctly. However, if the file is binary, the read-write file is very different from before and after reading and writing. Of course, replacing the above ReadLine () with read (char[]) is still not able to read and write the binary file correctly. Read and write binaries please keep looking at the following points.

Note that the offset in read (byte[] b, int offset, int length) is not the full-text of the full file, but the offset of byte array b

It is now known that using Reader/writer does not correctly read binary files because Reader/writer is a character stream, and then byte streams are used instead ufferedinputstream/bufferedoutputstream An example of an online search might be:

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 (DST File)); 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 at a time, then write 1024 bytes. This may seem quite right, but the actual written document is different from the original document. This may be a question of whether or not the read and write is not connected, and thus 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 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 inside. The offset in read (byte[] b, int offset, int length) actually refers to the placement of data from the position of the array (offset) when the read data is deposited into array B; Similarly, write (byte[] b, int Offset, int length) is the data in B, from which position (offset) to start writing to the file.

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

The second point of attention in the first paragraph of the code, although the practice is more common on the web, but there are problems. What's the problem? The answer is: The question is on the array of byte[] B. Because binary files use the comparison tool, you know only the different, but not the different, (whether there are more advanced comparison tools). )。 How to determine its difference. The method is simple: The binary file can be changed to a text file to see the results (Reader/writer this character stream, although not correctly read and write binary files, but inputstream/outputstream these byte streams can both read and write binary files correctly, can also read and write text files correctly). Because of the use of 1K (1024 bytes) per read, you will see the result: After the written file a paragraph, the length of the original file size and the size of the B array. To further determine what is the relationship between the contents of the read to "1234567890123", and the size of the B array to 10 bytes, then the result came out: the contents of the file into a "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, read two times, the first 10 bytes read, and then the elements in the B array are the first 10 characters, and the second time, because the readable content is only 3 characters, The contents of the B-array were changed only by the first 3 characters, and the last 7 characters remained the contents of the previous read. So directly using write (b), the second time when writing a file, the content is written more than a second read to the content.

The following are the correct reads and writes (that is, how much content is read at a time, how much is written, not 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 (DST File)); 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 Point four: Flush () and close ()

Flush () is the contents of the write buffer all "spit" on the file, without it, it is possible that a lot of content still exists in the write buffer, rather than in the file, that is, there is the possibility of loss.

Flush () is invoked in close (). It is the real completion of the file symbol, the file content is written to do not close the file stream, will cause some "odd" problem. This flow in the network is more manifest.

So, after writing the file, pay attention to turn off the file read and 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.