在java编程中,如何一个指定文件中的内容?
此示例显示如何使用BufferedReader
类的readLine()
方法读取文件。
package com.yiibai;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("F:/worksp/javaexamples/java_files/infile.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
System.out.println(str);
} catch (IOException e) {
}
}
}
执行上述示例代码,将产生以下结果 -
this is infile.txt content.
this is line2
this is line3
示例-2
以下是读取一个文件内容的另一个示例。
package com.yiibai;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile2 {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("F:/worksp/javaexamples/java_files/infile.txt"))) {
String sCurrentLine = null;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意:上面代码需要使用JDK7环境编译后运行。
执行上述示例代码,将产生以下结果 -
this is infile.txt content.
this is line2
this is line3