在Java中,似乎有不同的方式来读取和写入文件数据。
我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?
在Java中,似乎有不同的方式来读取和写入文件数据。
我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?
当前回答
我最喜欢的从BufferedReader输入读取整个文本文件的方法是:
字符串文本= input.lines().collect(collections .joining(System.lineSeparator())));
这将通过在每行后面添加新行(lineSeparator)来读取整个文件。如果没有分隔符,它会把所有的行连为一体。 这似乎从Java 8开始就存在了。
其他回答
ASCII是一个文本文件,因此您可以使用reader进行读取。Java还支持使用InputStreams从二进制文件中读取。如果要读取的文件很大,那么您可能希望在FileReader之上使用BufferedReader来提高读取性能。
阅读这篇关于如何使用Reader的文章
我还推荐你下载并阅读这本很棒(但免费)的书,叫做《用Java思考》
在Java 7中:
new String(Files.readAllBytes(...))
(文档) 或
Files.readAllLines(...)
(文档)
在Java 8中:
Files.lines(..).forEach(...)
(文档)
如果您有一个大文件,您可以使用Apache Commons IO迭代处理该文件,而不会耗尽可用内存。
try (LineIterator it = FileUtils.lineIterator(theFile, "UTF-8")) {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
}
对于基于jsf的Maven web应用程序,只需使用ClassLoader和Resources文件夹读取任何你想要的文件:
Put any file you want to read in the Resources folder. Put the Apache Commons IO dependency into your POM: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> Use the code below to read it (e.g. below is reading in a .json file): String metadata = null; FileInputStream inputStream; try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); inputStream = (FileInputStream) loader .getResourceAsStream("/metadata.json"); metadata = IOUtils.toString(inputStream); inputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return metadata;
您可以对文本文件、.properties文件、XSD模式等执行相同的操作。
可能没有缓冲I/O那么快,但是非常简洁:
String content;
try (Scanner scanner = new Scanner(textFile).useDelimiter("\\Z")) {
content = scanner.next();
}
\Z模式告诉扫描器分隔符是EOF。
这里有另一种不使用外部库的方法:
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;
}