在Java中,似乎有不同的方式来读取和写入文件数据。
我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?
在Java中,似乎有不同的方式来读取和写入文件数据。
我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?
当前回答
Java 11 Files.readString中引入了最直观的方法
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
public class App {
public static void main(String args[]) throws IOException {
String content = Files.readString(Paths.get("D:\\sandbox\\mvn\\my-app\\my-app.iml"));
System.out.print(content);
}
}
PHP几十年来一直享有这种特权!☺
其他回答
这里有另一种不使用外部库的方法:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public String readFile(String filename)
{
String content = null;
File file = new File(filename); // For example, foo.txt
FileReader reader = null;
try {
reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
reader.close();
}
}
return content;
}
在实践中,缓冲流类的性能要高得多,以至于NIO.2 API包含了专门返回这些流类的方法,部分原因是为了鼓励您始终在应用程序中使用缓冲流。
这里有一个例子:
Path path = Paths.get("/myfolder/myfile.ext");
try (BufferedReader reader = Files.newBufferedReader(path)) {
// Read from the stream
String currentLine = null;
while ((currentLine = reader.readLine()) != null)
//do your code here
} catch (IOException e) {
// Handle file I/O exception...
}
您可以替换此代码
BufferedReader reader = Files.newBufferedReader(path);
与
BufferedReader br = new BufferedReader(new FileReader("/myfolder/myfile.ext"));
我推荐这篇文章来学习Java NIO和IO的主要用途。
这基本上与Jesus Ramos的回答完全相同,除了使用File而不是FileReader加上迭代来逐级遍历文件的内容。
Scanner in = new Scanner(new File("filename.txt"));
while (in.hasNext()) { // Iterates each line in the file
String line = in.nextLine();
// Do something with line
}
in.close(); // Don't forget to close resource leaks
... 抛出FileNotFoundException
你想怎么处理这篇文章?文件是否小到可以装入内存?我会尽量找到最简单的方法来处理您需要的文件。FileUtils库可以很好地处理这个问题。
for(String line: FileUtils.readLines("my-text-file"))
System.out.println(line);
ASCII是一个文本文件,因此您可以使用reader进行读取。Java还支持使用InputStreams从二进制文件中读取。如果要读取的文件很大,那么您可能希望在FileReader之上使用BufferedReader来提高读取性能。
阅读这篇关于如何使用Reader的文章
我还推荐你下载并阅读这本很棒(但免费)的书,叫做《用Java思考》
在Java 7中:
new String(Files.readAllBytes(...))
(文档) 或
Files.readAllLines(...)
(文档)
在Java 8中:
Files.lines(..).forEach(...)
(文档)