Read method of Java-fileinputstream

Source: Internet
Author: User

Today a friend asks the Fileinputstrem method of the read () and read (Byte B) methods for what is used-one to judge the problem of reading the end of the file, here with everyone to learn.

    • About FileInputStream

It is used to read the byte data in the local file, inheriting from the InputStream class, since all the files are in bytes as wizards, so it works for any kind of file.

How do I use the two most important methods read () and read (Byte b)? Let's start by looking at the API documentation:

    • Read ()
 Public int  throws  IOException

Interpretation:

1, this method is to read from the input stream a byte of data, popular point, that is, every call read method, read a byte from the FileInputStream.

2, return the next data byte, if you have reached the end of the file, return-1, which is difficult to understand, in addition to the code to test the understanding is not difficult.

3. If no input is available, this method will block. This does not need to explain, everybody in the study time, uses the Scannner sc = new Scanner (system.in); System.in is InputStream (why?). Do not understand, please go to system.class check in what is a!! ), we all have a deep understanding that when executed into this code, will wait for the user input.

Since you can test any form of the file, then in two different formats, test files Data1.txt and Data2.txt, which are placed in 1 numbers "1", two files in the format: ANSI and Unicode.

Write a code test:

 PackageCom.gxlee;ImportJava.io.FileInputStream;Importjava.io.IOException; Public classTest { Public Static voidMain (string[] args)throwsIOException {fileinputstream fis=NewFileInputStream ("Data1.txt");//ANSI Format      for(inti = 0; I < 5; i++) {System.out.println (Fis.read ());         } fis.close (); System.out.println ("------------------"); FIS=NewFileInputStream ("Data2.txt");//Unicode format      for(inti = 0; I < 5; i++) {System.out.println (Fis.read ());    } fis.close (); }}

Isn't there a single number in the file, why the Loop 5 times, what ghost? Later, we'll look at the output:

49-1-1-1-1
------------------255254490-1

How did it end up like this?

1. Because the ANSI encoding does not have a file header, the numeric character 1 is only one byte, and 1 of the ASCII code is 49 so output 49, and the Unicode format has 2 bytes of the file header, and a character in 2 bytes, the corresponding character for the ASCII character is the 2nd bit 0, Therefore, the two-bit decimal of 1 Unicode code is 49 and 0 respectively;

Attached: Text file Format file header: ANSI type: Nothing, UTF-8 type: EF BB bf,unicode type: FF fe,unicode BIG endian type: FE FF

2. From the returned results, the current byte data is returned, the original in the API document is: "The next data byte, if the end of the file has been reached, then return -1 ." The next byte of data, or -1 if the end of the file is reached, should be understood as: At this point the pointer is at the beginning of the next data byte. As indicated:

Therefore, for files of unknown length, it is possible to determine whether the read is finished by reading to-one, and the following is the code snippet:

intwhile ( -1!= (b=fis.read ())) {    System.err.println (b);}
    • Read (Byte b)

Also look at the API:

 Public int Read (bytethrows IOException
BYTE-


Interpretation:

1, up to b.length bytes of data are read into a byte data set, that is, a maximum of byte array b is filled;

2. Returns the total number of bytes read into the buffer, or 1 if there is no more data since the end of the file has been reached. Here is the question point for friends, why use-to determine the end of the file. His reason is, suppose 3 bytes of source data, with 2 byte array to cache, when the 2nd time to read the time to reach the end of the file, this time should return 1, not only read 2 bytes?

Again, let's test:

Test file, data.txt, file format ANSI, file content 123, test code:

 PackageCom.gxlee;ImportJava.io.FileInputStream;Importjava.io.IOException;Importjava.util.Arrays; Public classTest { Public Static voidMain (string[] args)throwsIOException {fileinputstream fis=NewFileInputStream ("Data.txt");//ANSI Format     byte[] B =New byte[2];  for(inti = 0; I < 3; i++) {System.out.print ("First" + (i+1) + "secondary read results returned:" +Fis.read (b)); System.out.println ("After reading, the contents of array B are:" +arrays.tostring (b));    } fis.close (); }}

Output Result:

The 1th reads the returned result: 2, after reading the contents of the array B is: [, 1] The 2nd reads the result of the return:1, after reading the contents of the array B is: [Wuyi,] 3rd reads the result of the return:-the second reading of the contents of array B is: [51, 50]

The test data file is in ANSI format, put 3 digits, so it is 3 bytes, here the test read 3 times, from the code can be seen, B is a byte array, the size of 2, that is, each can hold 2 bytes. So the problem comes, read the first time read to 2 bytes return very good understanding, and the 2nd time, because there is only one byte, here to the end of the file, according to the friend of the API document understanding, should return 1?
API documentation is only a textual description of the source code, the specific meaning of the reader's understanding is biased, then we look at the source code it?

 Public int Read (bytethrows  ioexception {    return readbytes (b, 0, B.length); }

Also called the Readbytes method, continue to see the source of the method:

Private native int readbytes (byteintintthrows IOException;

Bolt from the blue, is a native modified method, so there is no way to continue to look at the code. There is nothing to say, inherit FileInputStream with a code class, overwrite the read (byte b) method, see the code to understand:

 PackageCom.gxlee;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException; Public class MyFileInputStreamextendsfileinputstream{ PublicMyfileinputstream (String name)throwsFileNotFoundException {Super(name); } @Override Public intReadbyte[] b)throwsIOException {intGetData =read (); if(Getdata==-1) {            return-1; }Else{b[0] = (byte) GetData;  for(inti = 1; i < b.length; i++) {GetData=read (); if( -1==getData)returni; B[i]= (byte) GetData; }        }        returnb.length; }}

The original test code made a small change:

 PackageCom.gxlee;ImportJava.io.FileInputStream;Importjava.util.Arrays; Public classTest { Public Static voidMain (string[] args)throwsException {fileinputstream fis=New MyFileInputStream ("Data.txt");//ANSI Format         byte[] B =New byte[2];  for(inti = 0; I < 3; i++) {System.out.print ("First" + (i+1) + "secondary read results returned:" +Fis.read (b)); System.out.println ("After reading, the contents of array B are:" +arrays.tostring (b));        } fis.close (); }}

The output is consistent with the original result:

The 1th reads the returned result: 2, after reading the contents of the array B is: [, 1] The 2nd reads the result of the return:1, after reading the contents of the array B is: [Wuyi,] 3rd reads the result of the return:-the second reading of the contents of array B is: [51, 80°

Icon:

The understanding of the hands of the people, each grasp.

Test Read text content:

 PackageCom.gxlee;ImportJava.io.FileInputStream; Public classTest { Public Static voidMain (string[] args)throwsException {fileinputstream fis=NewMyfileinputstream ("Data.txt");//ANSI Format         byte[] B =New byte[2]; intLen;  while( -1!= (len =Fis.read (b))) {System.out.println (NewString (b,0, Len)); }                  Fis.close (); }}

Accurate output file content:

123

Original content, welcome guidance!

Read method of Java-fileinputstream

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.