read complete file without using loop in java

后端 未结 5 1870
长情又很酷
长情又很酷 2020-11-28 05:05

Possible Duplicate:
How to create a Java String from the contents of a file
Whole text file to a String in Java

相关标签:
5条回答
  • 2020-11-28 05:32

    Java 7 one line solution

    List<String> lines = Files.readAllLines(Paths.get("file"), StandardCharsets.UTF_8);
    

    or

     String text = new String(Files.readAllBytes(Paths.get("file")), StandardCharsets.UTF_8);
    
    0 讨论(0)
  • 2020-11-28 05:35

    If you are using Java 5/6, you can use Apache Commons IO for read file to string. The class org.apache.commons.io.FileUtils contais several method for read files.

    e.g. using the method FileUtils#readFileToString:

    File file = new File("abc.txt");
    String content = FileUtils.readFileToString(file);
    
    0 讨论(0)
  • 2020-11-28 05:39

    If the file is small, you can read the whole data once:

    File file = new File("a.txt");
    FileInputStream fis = new FileInputStream(file);
    byte[] data = new byte[(int) file.length()];
    fis.read(data);
    fis.close();
    
    String str = new String(data, "UTF-8");
    
    0 讨论(0)
  • 2020-11-28 05:45

    Since Java 11 you can do it even simpler:

    import java.nio.file.Files;
    
    Files.readString(Path path);
    Files.readString​(Path path, Charset cs)
    

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

    0 讨论(0)
  • 2020-11-28 05:49

    You can try using Scanner if you are using JDK5 or higher.

    Scanner scan = new Scanner(file);  
    scan.useDelimiter("\\Z");  
    String content = scan.next(); 
    

    Or you can also use Guava

    String data = Files.toString(new File("path.txt"), Charsets.UTF8);
    
    0 讨论(0)
提交回复
热议问题