Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

How to get file content in java?

to get the content of a txt file I usually use a scanner and iterate over each line to get the content:

Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();                     
}

Does the java api provide a way to get the content with one line of code like:

String content = FileUtils.readFileToString(new File("file.txt"))
question from:https://stackoverflow.com/questions/5641100/how-to-get-file-content-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not the built-in API - but Guava does, amongst its other treasures. (It's a fabulous library.)

String content = Files.toString(new File("file.txt"), Charsets.UTF_8);

There are similar methods for reading any Readable, or loading the entire contents of a binary file as a byte array, or reading a file into a list of strings, etc.

Note that this method is now deprecated. The new equivalent is:

String content = Files.asCharSource(new File("file.txt"), Charsets.UTF_8).read();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...