如何在java中获取文件内容?

Upv*_*ote 34 java java-io

要获取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)

  • 很酷,您也可以使用readAllBytes()并执行以下一个没有任何第三方库的内联:String content = new String(Files.readAllBytes(new File("/ my/file.txt")).toPath())) (5认同)

Boz*_*zho 15

commons-io有:

IOUtils.toString(new FileReader("file.txt"), "utf-8");
Run Code Online (Sandbox Code Playgroud)


Tho*_*ger 8

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)

来自https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)


小智 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)