Java Java类
FileInputStream 类对于以字节序列的形式从文件中读取数据很有用。 FileInputStream 用于读取原始字节流,例如图像数据。要读取字符流,请考虑使用 FileReader。
FileInputStream 类的构造函数
1. FileInputStream(File file):创建一个输入文件流,从指定的File对象中读取。
2. FileInputStream(FileDescriptor fdobj):创建一个输入文件流,从指定的文件描述符中读取。
3. FileInputStream(String name):创建一个输入文件流以从具有指定名称的文件中读取。
FileInputStream 类的方法Methods Action Performed available() Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream. close() Closes this file input stream and releases any system resources associated with the stream. finalize() Ensures that the close method of this file input stream is called when there are no more references to it. getChannel() Returns the unique FileChannel object associated with this file input stream. getFD() Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream. read() Reads a byte of data from this input stream read(byte[] b) Reads up to b.length bytes of data from this input stream into an array of bytes. read(byte[] b, int off, int len) Reads up to len bytes of data from this input stream into an array of bytes. skip() Skips over and discards n bytes of data from the input stream
现在,当我们确实使用这些方法时,我们通常按照这些步骤使用 FileInputStream 从文件中读取数据,这是 FileInputClass 的最后通牒目标
第 1 步:将文件附加到 FileInputStream,因为这将使我们能够从文件中读取数据,如下所示:
FileInputStream fileInputStream =new FileInputStream(“file.txt”);
第 2 步:现在为了从文件中读取数据,我们应该从 FileInputStream 中读取数据,如下所示:
ch=fileInputStream.read();
步骤 3-A:当没有更多数据可供进一步读取时,read() 方法返回 -1;
步骤 3-B:然后我们应该将监视器附加到输出流。为了显示数据,我们可以使用 System.out.print。
System.out.print(ch);
执行:
原始文件内容:
This is my first line
This is my second line
例子:
Java
// Java Program to Demonstrate FileInputStream Class
// Importing I/O classes
import java.io.*;
// Main class
// ReadFile
class GFG {
// Main driver method
public static void main(String args[])
throws IOException
{
// Attaching the file to FileInputStream
FileInputStream fin
= new FileInputStream("file1.txt");
// Illustrating getChannel() method
System.out.println(fin.getChannel());
// Illustrating getFD() method
System.out.println(fin.getFD());
// Illustrating available method
System.out.println("Number of remaining bytes:"
+ fin.available());
// Illustrating skip() method
fin.skip(4);
// Display message for better readability
System.out.println("FileContents :");
// Reading characters from FileInputStream
// and write them
int ch;
// Holds true till there is data inside file
while ((ch = fin.read()) != -1)
System.out.print((char)ch);
// Close the file connections
// using close() method
fin.close();
}
}
输出:
sun.nio.ch.FileChannelImpl@1540e19d
java.io.FileDescriptor@677327b6
Number of remaining bytes:45
FileContents :
is my first line
This is my second line