In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use java's FileInputStream stream". In daily operation, I believe many people have doubts about how to use java's FileInputStream stream. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use java's FileInputStream stream". Next, please follow the editor to study!
I. the concept of File flow
JAVA sets up a series of streams for reading and writing files, among which there are four most commonly used streams in FileInputStream,FileOutputStream,FileReader,FileWriter.
II. FileInputStream1) FileInputStream concept
FileInputStream stream is called file byte input stream, which means to read file data in bytes, such as reading pictures and videos, etc.
2) Construction method
2.1) create a FileInputStream stream object by opening a link to the actual file represented by the File class object
Public FileInputStream (File file) throws FileNotFoundException {}
If the file represented by the File class object does not exist; it is not a file but a directory; or if it cannot be opened for other reasons, a FileNotFoundException will be thrown
/ * * running will generate an exception and be caught-- because there is no file like xxxxxxxx * / public static void main (String [] args) {File file=new File ("xxxxxxxx") / / create a File class object according to the path-- here the path will not report an error even if there is an error, because it only generates a File object and is not associated with computer file reading and writing try {FileInputStream fileInputStream=new FileInputStream (file) / / create a fileInputStream object} catch (FileNotFoundException e) {System.out.println ("the file does not exist or the file is not readable or the file is a directory") based on the actual file represented by the File class object;}}
2.2) create a File class object with the specified string parameters, and then establish a link with the actual path represented by the File object to create a FileInputStream stream object
Public FileInputStream (String name) throws FileNotFoundException
By looking at the source code, it is found that the construction method is extended on the basis of the first construction method, so the rules are consistent with the first construction method.
Public FileInputStream (String name) throws FileNotFoundException {this (name! = null? New File (name): null);}
This construction method is not understood-viewing api refers to the use of fdObj file descriptors as parameters, and file descriptors refer to connections to files in the computer system. The source code of the first two methods finally uses file descriptors to establish connections.
Public FileInputStream (FileDescriptor fdObj) 3) FileInputStream commonly used API
3.1) read a byte from the input stream and return an int variable, or-1 if the end of the file is reached
Public int read () throws IOException
Understand why read bytes return int variables
1. The-1 in the method interpretation is equivalent to the data dictionary telling the caller that the file has been finished and can be read at the end. The-1 here is int.
2. When the file is not in the end, we are reading bytes. If the byte type is returned, it is bound to cause different return types of the same method, which is not allowed.
3. The byte we read is actually composed of 8-bit binary, and the binary file is not conducive to visual viewing, so it can be converted to the commonly used decimal system for display, so it is necessary to convert the read byte from binary to decimal integer, so int is returned.
4. Therefore, combined with the above three points, the return type is consistent and can be viewed intuitively, so although the method reads bytes, it returns int type.
The read method reads the instance-- the final output is consistent with the character content.
Package com.test; import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException; public class FileStream {/ * / public static void main (String [] args) {/ / create a file object File file=new File ("C:\\ Users\\ Administrator\\ Desktop\\ 1.txt") Try {/ / set up a link FileInputStream fileInputStream=new FileInputStream (file); int nasty 0; StringBuffer sBuffer=new StringBuffer (); while (natively equal to 1) / / if n is not equal to-1, it means not to the end {n=fileInputStream.read () / / read a byte of the file (8 binary bits) and convert it from binary to decimal integer to return char by= (char) n; / / to character sBuffer.append (by);} System.out.println (sBuffer.toString ()) } catch (FileNotFoundException e) {System.out.println ("File does not exist or the file is not readable or the file is a directory");} catch (IOException e) {System.out.println ("exception exists in the read process");}
Read b.length bytes from the input stream into the byte array and return the total number of bytes read into the buffer, or-1 if the end of the file is reached
Public int read (byte [] b) throws IOException
1. Let's first set up a buffer, that is, a byte array that is used to store the byte data read from the stream. The length of the array is N
two。 Then read N bytes from the stream into the byte array. However, note that the total number of bytes read is returned instead of N, indicating that sometimes the total number of bytes actually read is not necessarily equal to the length of the array
3. The content of the document is 12345. So there are 5 bytes in the stream, but we set the byte array length to 2. 5. So how many times will you read it? What's the situation like every time?
Public class FileStream {public static void main (String [] args) {/ / create a file object File file=new File ("C:\\ Users\\ Administrator\\ Desktop\\ 1.txt"); try {/ / create a link FileInputStream fileInputStream=new FileInputStream (file); int [] b=new byte [2] Int iBytes 0; while (nasty colors 1) / / if n is not equal to-1, it represents the end {n=fileInputStream.read (b); / / returns the number of bytes actually read into the byte array System.out.println (n) System.out.println (Arrays.toString (b)); / / read the contents of the byte array; System.out.println ("execution times:" + I);} System.out.println (new String (b)) } catch (FileNotFoundException e) {System.out.println ("File does not exist or the file is not readable or the file is a directory");} catch (IOException e) {System.out.println ("exception exists in the read process");}
The actual implementation results are as follows:
As you can see, the length of the array is 2, so the first time you read 2 bytes into the array, the array is filled. There are 3 bytes left in the stream to continue reading
The second read still reads 2 bytes into the array, and the contents of the array are replaced. At this point, there is only 1 byte left in the stream. According to API, read the array length (2) bytes into the array, but then you can no longer read 2 bytes. Should we stop?
The actual process did not stop, but the third read, only the remaining 1 byte, and replaced to the array in the 0 subscript position.
Then on the fourth read, it was found that it moved to the end and returned-1. Stop reading
So there is a doubt here-why can you continue to read when there is only 1 byte left and the requirement is to read 2 bytes?
Then we look at the source code of this method and find that it is essentially other methods called readBytes (b, 0, b.length).
Public int read (byte b []) throws IOException {return readBytes (b, 0, b.length);}
Continue to look at the readBytes (b, 0, b.length) method is that the native method represents that the method has an implementation body but is not implemented in Java, resulting in no way to see the specific implementation.
But it can be understood that parameter b is the array we set, 0 is int, and the last parameter is the length of the array.
Private native int readBytes (byte b [], int off, int len) throws IOException
So we look at InputStream, the parent class of FileInputStream, and find that there is an implementation of this method.
Let's now consider the method execution on the third read, when b is [51 552]. Off is 0 and len is 2. There is only one byte in the data stream.
If else if's judgment of this condition is found to be inconsistent, so continue to carry out.
Read ()-- this method represents reading a byte from the stream, and there happens to be another byte in the stream at this time, so there is no problem with the method execution. The return value is 53
Continue to execute discovery b [0] = (byte) 53. That is, the int type read is converted to bytes and stored in the first position in the array, where the array content is [537552]
Continue execution into the for loop, where there are no bytes in the stream, then the read () method returns not-1 to exit the loop. The value of the return variable I is 1.
That is, this method execution reads 1 byte into the array. And read to the end of the file, so the fourth execution to the int c=read () method has returned-1, and does not replace the value in the array
Public int read (byte b [], int off, int len) throws IOException {if (b = = null) {throw new NullPointerException ();} else if (off)
< 0 || len < 0 || len >B.length-off) {throw new IndexOutOfBoundsException ();} else if (len = = 0) {return 0;} int c = read (); if (c = =-1) {return-1;} b [off] = (byte) c; int i = 1; try {for (; I
< len ; i++) { c = read(); if (c == -1) { break; } b[off + i] = (byte)c; } } catch (IOException ee) { } return i; } 读取过程图解:4. Suppose there are 5 bytes in the stream, but the byte array length we set is 10, how many times do we read it? What's the situation like every time?
Public class FileStream {public static void main (String [] args) {/ / create a file object File file=new File ("C:\\ Users\\ Administrator\\ Desktop\\ 1.txt"); try {/ / create a link FileInputStream fileInputStream=new FileInputStream (file); int [] b=new byte [10] Int iBytes 0; while (nasty colors 1) / / if n is not equal to-1, it represents the end {n=fileInputStream.read (b); / / returns the number of bytes actually read into the byte array System.out.println (n) System.out.println (Arrays.toString (b)); / / read the contents of the byte array; System.out.println ("execution times:" + I);} System.out.println (new String (b)) } catch (FileNotFoundException e) {System.out.println ("File does not exist or the file is not readable or the file is a directory");} catch (IOException e) {System.out.println ("exception exists in the read process");}
The implementation results are as follows:
Combined with the source code mentioned above, we can find that the for loop in the source code, although the len is 10 (the length of the array), the bytes in the stream have been read and the pointer is moved to the end of the file, so the for loop will not continue. And return 5, which coincides with the actual reading of 5 bytes into the array for the first time in the result. The pointer reached the end on the second read. So int c = read () returns-1 here. The method is over, the array is not changed and the for loop is not repeated
But there is a problem with this situation: five positions in the array are wasted and there is no data in it.
Specific reading illustration:
Combining the above two cases, it is found that the array length is very important when using the read (byte b []) method, and if the length is less than the byte length of the stream, the resulting content will be lost. If it is larger than the byte length of the stream, the memory of the last array will be wasted, so the length of the array needs to be set according to the byte length of the file.
Byte [] b=new byte [(int) file.length ()]
Read up to len bytes from the input stream to the byte array (storing bytes from the off position of the array), return 0 when len is 0, if len is not zero, the method will block until some inputs are available-doubtful here
Public int read (byte [] bmenint off,int len) throws IOException
The source code is as follows
Public int read (byte b [], int off, int len) throws IOException {if (b = = null) {throw new NullPointerException ();} else if (off)
< 0 || len < 0 || len >B.length-off) {throw new IndexOutOfBoundsException ();} else if (len = = 0) {return 0;} int c = read (); if (c = =-1) {return-1;} b [off] = (byte) c; int i = 1; try {for (; I < len) Break; +) {c = read (); if (c =-1) {break;} b [off + I] = (byte) c;}} catch (IOException ee) {} return I;}
3.4) close this input stream and release all system resources associated with the stream-that is, release the connection to the actual file (looking at the source code shows that there is a synchronous lock on the resource, so close the stream to release the lock)
Efficiency comparison of three and three read methods of public void close () throws IOException
1. Check the source code of the three read methods, whose essence is to use the for loop to read the content in a single byte.
2. From the point of view of the code form, using read (byte [] b) is more intuitive and simple, so this method can be used for data reading in the project.
At this point, the study on "how to use java's FileInputStream stream" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.