示例 1: Java 程序使用 BufferedInputStream 读取文件
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: Java 程序使用 BufferedReader 读取文件
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 Class来读取名为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
对象。
这里,我们使用了扫描仪方法
hasNextLine()-如果文件中有下一行,则返回 true
nextLine()-从文件中返回整行
要了解有关扫描仪的更多信息,请访问 Java 扫描仪。