要获取txt文件的内容,我通常使用扫描仪并遍历每一行以获取内容:
Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
String str = sc.nextLine();
}
Run Code Online (Sandbox Code Playgroud)
java api是否提供了使用一行代码获取内容的方法,如:
String content = FileUtils.readFileToString(new File("file.txt"))
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 26
不是内置的API - 但是Guava确实是其他宝藏之一.(这是一个神话般的图书馆.)
String content = Files.toString(new File("file.txt"), Charsets.UTF_8);
Run Code Online (Sandbox Code Playgroud)
有类似的方法可以读取任何Readable,或者将二进制文件的全部内容作为字节数组加载,或者将文件读入字符串列表等.
ric*_*ich 16
使用Java 7,沿着这些行有一个API.
Files.readAllLines(Path path,Charset cs)
Boz*_*zho 15
IOUtils.toString(new FileReader("file.txt"), "utf-8");
Run Code Online (Sandbox Code Playgroud)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public static void main(String[] args) throws IOException {
String content = Files.readString(Paths.get("foo"));
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以将FileReader类与BufferedReader一起使用以读取文本文件。
File fileToRead = new File("file.txt");
try( FileReader fileStream = new FileReader( fileToRead );
BufferedReader bufferedReader = new BufferedReader( fileStream ) ) {
String line = null;
while( (line = bufferedReader.readLine()) != null ) {
//do something with line
}
} catch ( FileNotFoundException ex ) {
//exception Handling
} catch ( IOException ex ) {
//exception Handling
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77766 次 |
| 最近记录: |