示例 1:使用BufferedInputStream读取文件的Java程序
import java.io.BufferedInputStream;
import java.io.FileInputStream;
class Main {
public static void main(String[] args) {
try {
// Creates a FileInputStream
FileInputStream file = new FileInputStream("input.txt");
// Creates a BufferedInputStream
BufferedInputStream input = new BufferedInputStream(file);
// Reads first byte from file
int i = input .read();
while (i != -1) {
System.out.print((char) i);
// Reads next byte from the file
i = input.read();
}
input.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
输出
First Line Second Line Third Line Fourth Line Fifth Line
在上面的示例中,我们使用BufferedInputStream
类从名为input.txt的文件中读取每一行。
注意:要运行此文件,您应该在当前工作目录中有一个名为input.txt的文件。
示例 2:使用BufferedReader读取文件的Java程序
import java.io.FileReader;
import java.io.BufferedReader;
class Main {
public static void main(String[] args) {
// Creates an array of character
char[] array = new char[100];
try {
// Creates a FileReader
FileReader file = new FileReader("input.txt");
// Creates a BufferedReader
BufferedReader input = new BufferedReader(file);
// Reads characters
input.read(array);
System.out.println("Data in the file: ");
System.out.println(array);
// Closes the reader
input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
输出
Data in the file: First Line Second Line Third Line Fourth Line Fifth Line
在上面的示例中,我们使用了BufferedReader类来读取名为input.txt的文件。
示例 3:使用Scanner读取文件的Java程序
import java.io.File;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
try {
// create a new file object
File file = new File("input.txt");
// create an object of Scanner
// associated with the file
Scanner sc = new Scanner(file);
// read each line from file and print it
System.out.println("Reading File Using Scanner:");
while(sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
// close scanner
sc.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}
输出
Reading File Using Scanner: First Line Second Line Third Line Fourth Line Fifth Line
在上面的示例中,我们创建了一个名为file的File
类对象。然后,我们创建了一个与file关联的Scanner
对象。
在这里,我们使用了Scanner的方法
- hasNextLine() - 如果文件中存在下一行,则返回true
- nextLine() - 从文件中返回整行
要了解更多关于Scanner的信息,请访问Java Scanner。