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

| 要获取txt文件的内容,我通常使用扫描仪并遍历每行以获取内容:
Scanner sc = new Scanner(new File(\"file.txt\"));
while(sc.hasNextLine()){
    String str = sc.nextLine();                     
}
java api是否提供一种通过一行代码获取内容的方法,例如:
String content = FileUtils.readFileToString(new File(\"file.txt\"))
    
已邀请:
在Java 7中,这些方面都有一个API。 Files.readAllLines(路径路径,字符集cs)     
除了内置的API以外,Guava还有其他一些宝藏。 (这是一个很棒的图书馆。)
String content = Files.toString(new File(\"file.txt\"), Charsets.UTF_8);
有类似的方法可读取任何Readable或将二进制文件的全部内容加载为字节数组,或将文件读取到字符串列表中,等等。 请注意,现在不建议使用此方法。新的等效项是:
String content = Files.asCharSource(new File(\"file.txt\"), Charsets.UTF_8).read();
    
commons-io具有:
IOUtils.toString(new FileReader(\"file.txt\"), \"utf-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\"));
}
来自https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)     
您可以将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
}
    

要回复问题请先登录注册