Java io fileinputstream readbytes native method

How to read file in Java – FileInputStream

In Java, we use FileInputStream to read bytes from a file, such as an image file or binary file.

Note
However, all the below examples use FileInputStream to read bytes from a text file and print them out. The text file allows readers to «see» the output correctly. Generally, we use Reader to read characters from a text file.

1. FileInputStream – Read a file

This example uses FileInputStream to read bytes from a file and print out the content. The fis.read() reads a byte at a time, and it will return a -1 if it reached the end of the file.

 package com.mkyong.io.api.inputstream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FileInputStreamExample1 < public static void main(String[] args) < readFile("c:\\test\\file.txt"); >private static void readFile(String fileName) < try (FileInputStream fis = new FileInputStream(new File(fileName))) < int content; // reads a byte at a time, if it reached end of the file, returns -1 while ((content = fis.read()) != -1) < System.out.println((char)content); >> catch (IOException e) < e.printStackTrace(); >> > 

2. FileInputStream – Remaining bytes

We can use fis.available() to check the remaining bytes that can be read. For example:

Below is a text file containing 10 bytes.

read file

 package com.mkyong.io.api.inputstream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FileInputStreamExample2 < public static void main(String[] args) < readFile("c:\\test\\file.txt"); >private static void readFile(String fileName) < try (FileInputStream fis = new FileInputStream(new File(fileName))) < // remaining bytes that can be read System.out.println("Remaining bytes that can be read : " + fis.available()); int content; // reads a byte at a time, if end of the file, returns -1 while ((content = fis.read()) != -1) < System.out.println((char) content); System.out.println("Remaining bytes that can be read : " + fis.available()); >> catch (IOException e) < e.printStackTrace(); >> > 
 Remaining bytes that can be read : 10 m Remaining bytes that can be read : 9 k Remaining bytes that can be read : 8 y Remaining bytes that can be read : 7 o Remaining bytes that can be read : 6 n Remaining bytes that can be read : 5 g Remaining bytes that can be read : 4 . Remaining bytes that can be read : 3 c Remaining bytes that can be read : 2 o Remaining bytes that can be read : 1 m Remaining bytes that can be read : 0 

For a file containing 10 bytes file, the fis.read() will run ten times and read a byte for each time. (See the problem here?)

3. FileInputStream – Better performance

3.1 Review the FileInputStream#read() source code, each read() will call the native method to read a byte from the disk.

 package java.io; public class FileInputStream extends InputStream < /** * Reads a byte of data from this input stream. This method blocks * if no input is yet available. * * @return the next byte of data, or -1 if the end of the * file is reached. * @exception IOException if an I/O error occurs. */ public int read() throws IOException < return read0(); >private native int read0() throws IOException; //. > 

3.2 We can use the read(byte b[]) to read predefined bytes into a byte array; it will significantly increase the read performance.

 package com.mkyong.io.api.inputstream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class FileInputStreamExample3 < public static void main(String[] args) < readFileBetterPerformance("c:\\test\\file.txt"); >private static void readFileBetterPerformance(String fileName) < try (FileInputStream fis = new FileInputStream(new File(fileName))) < // remaining bytes that can be read System.out.println("Remaining bytes that can be read : " + fis.available()); // 8k a time byte[] bytes = new byte[8192]; // reads 8192 bytes at a time, if end of the file, returns -1 while (fis.read(bytes) != -1) < // convert bytes to string for demo System.out.println(new String(bytes, StandardCharsets.UTF_8)); System.out.println("Remaining bytes that can be read : " + fis.available()); >> catch (IOException e) < e.printStackTrace(); >> > 

The above example will read 8192 bytes at a time, and for a file containing 10 bytes, it reads only one time.

 Remaining bytes that can be read : 10 mkyong.com Remaining bytes that can be read : 0 

Note
For example, if a file containing 81920 bytes (80 kb), the default fis.read will require an 81920 native calls to read all bytes from the file; While the fis.read(bytes) (for a size of 8192), we only need 10 native calls. The difference is enormous.

Читайте также:  Ссылки

4. FileInputStream vs BufferedInputStream

The FileInputStream reads a byte at a time, and each read() will be a native read from the disk. For reading a large file, it will slow.

The BufferedInputStream reads 8192 bytes (default) at a time and buffers them until they are needed; The BufferedInputStream#read() still returns a single byte at a time, but other remaining bytes are in the buffer and reserved for the next read. The concept is similar to the above FileInputStreamExample3.java

The common practice uses BufferedInputStream to wrap the FileInputStream to provide a buffer cache to increase the read performance.

 package com.mkyong.io.api.inputstream; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FileInputStreamExample4 < public static void main(String[] args) < readFileBetterPerformance2("c:\\test\\file.txt"); >private static void readFileBetterPerformance2(String fileName) < try (BufferedInputStream bis = new BufferedInputStream( new FileInputStream(new File(fileName)))) < // remaining bytes that can be read System.out.println("Remaining bytes that can be read : " + bis.available()); int content; // reads 8192 bytes at a time and buffers them until they are needed, // if end of the file, returns -1 while ((content = bis.read()) != -1) < // convert bytes to string for demo System.out.println((char) content); System.out.println("Remaining bytes that can be read : " + bis.available()); >> catch (IOException e) < e.printStackTrace(); >> > 
 Remaining bytes that can be read : 10 m Remaining bytes that can be read : 9 k Remaining bytes that can be read : 8 y Remaining bytes that can be read : 7 o Remaining bytes that can be read : 6 n Remaining bytes that can be read : 5 g Remaining bytes that can be read : 4 . Remaining bytes that can be read : 3 c Remaining bytes that can be read : 2 o Remaining bytes that can be read : 1 m Remaining bytes that can be read : 0 

5. Convert FileInputStream to Reader

It’s also common to use InputStreamReader to convert InputStream to a Reader .

This example shows how to convert a FileInputStream to BufferedReader , and read it line by line.

 private static void readFileBetterInputStreamReader(String fileName) < try (BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(new File(fileName))))) < String line; while ((line = br.readLine()) != null) < System.out.println(line); >> catch (IOException e) < e.printStackTrace(); >> 

6. FileInputStream – Read a Unicode file

This example uses FileInputStream to read a Unicode file. For example:

A Unicode file containing a few Chinese characters, and each Unicode code character contains two or more bytes.

Читайте также:  Python create dict from lists

unicode file

We can use the above example 3 to read the Unicode file and print them correctly.

 private static void readFileBetterPerformance(String fileName) < try (FileInputStream fis = new FileInputStream(new File(fileName))) < // remaining bytes that can be read System.out.println("Remaining bytes that can be read : " + fis.available()); // 8k a time byte[] bytes = new byte[8192]; // reads 8192 bytes at a time, if end of the file, returns -1 while (fis.read(bytes) != -1) < // convert bytes to string for demo // convert bytes unicode to string System.out.println(new String(bytes, StandardCharsets.UTF_8)); System.out.println("Remaining bytes that can be read : " + fis.available()); >> catch (IOException e) < e.printStackTrace(); >> 
 Remaining bytes that can be read : 25 你好 我好 大家好 Remaining bytes that can be read : 0 

Furthermore, we also can use the example 5 InputStreamReader to read and print the Unicode file, by default the InputStreamReader has a default charset of UTF-8.

Источник

Java io fileinputstream readbytes native method

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader .

Constructor Summary

Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

Creates a FileInputStream by using the file descriptor fdObj , which represents an existing connection to an actual file in the file system.

Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

Method Summary

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Ensures that the close method of this file input stream is called when there are no more references to it.

Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream .

Methods inherited from class java.io.InputStream

Methods inherited from class java.lang.Object

Constructor Detail

FileInputStream

public FileInputStream(String name) throws FileNotFoundException

Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system. A new FileDescriptor object is created to represent this file connection. First, if there is a security manager, its checkRead method is called with the name argument as its argument. If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown.

FileInputStream

public FileInputStream(File file) throws FileNotFoundException

Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system. A new FileDescriptor object is created to represent this file connection. First, if there is a security manager, its checkRead method is called with the path represented by the file argument as its argument. If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown.

FileInputStream

Creates a FileInputStream by using the file descriptor fdObj , which represents an existing connection to an actual file in the file system. If there is a security manager, its checkRead method is called with the file descriptor fdObj as its argument to see if it’s ok to read the file descriptor. If read access is denied to the file descriptor a SecurityException is thrown. If fdObj is null then a NullPointerException is thrown. This constructor does not throw an exception if fdObj is invalid . However, if the methods are invoked on the resulting stream to attempt I/O on the stream, an IOException is thrown.

Читайте также:  Подчеркивание у ссылок

Method Detail

read

read

Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

read

Reads up to len bytes of data from this input stream into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.

skip

Skips over and discards n bytes of data from the input stream. The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0 . If n is negative, the method will try to skip backwards. In case the backing file does not support backward skip at its current position, an IOException is thrown. The actual number of bytes skipped is returned. If it skips forwards, it returns a positive value. If it skips backwards, it returns a negative value. This method may skip more bytes than what are remaining in the backing file. This produces no exception and the number of bytes skipped may include some number of bytes that were beyond the EOF of the backing file. Attempting to read from the stream after skipping past the end will result in -1 indicating the end of the file.

available

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. Returns 0 when the file position is beyond EOF. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. In some cases, a non-blocking read (or skip) may appear to be blocked when it is merely slow, for example when reading large files over slow networks.

close

Closes this file input stream and releases any system resources associated with the stream. If this stream has an associated channel then the channel is closed as well.

getFD

Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream .

getChannel

Returns the unique FileChannel object associated with this file input stream. The initial position of the returned channel will be equal to the number of bytes read from the file so far. Reading bytes from this stream will increment the channel’s position. Changing the channel’s position, either explicitly or by reading, will change this stream’s file position.

finalize

Ensures that the close method of this file input stream is called when there are no more references to it.

Источник

Оцените статью