在Java中,似乎有不同的方式来读取和写入文件数据。
我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?
在Java中,似乎有不同的方式来读取和写入文件数据。
我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?
当前回答
最简单的方法是使用Java中的Scanner类和FileReader对象。简单的例子:
Scanner in = new Scanner(new FileReader("filename.txt"));
扫描器有几个方法读取字符串,数字,等…您可以在Java文档页面上查找有关这方面的更多信息。
例如,将整个内容读入String:
StringBuilder sb = new StringBuilder();
while(in.hasNext()) {
sb.append(in.next());
}
in.close();
outString = sb.toString();
另外,如果你需要一个特定的编码,你可以使用这个来代替FileReader:
new InputStreamReader(new FileInputStream(fileUtf8), StandardCharsets.UTF_8)
其他回答
对于使用Kotlin的Android开发者来说:
val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val text = myFileUrl.readText() // Not recommended for huge files
println(text)
其他解决方案:
val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val file = File(myFileUrl.toURI())
val lines = file.readLines() // Not recommended for huge files
lines.forEach(::println)
另一个很好的解决方案,也可以用于大文件:
val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val file = File(myFileUrl.toURI())
file
.bufferedReader()
.lineSequence()
.forEach(::println)
Or:
val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val file = File(myFileUrl.toURI())
file.useLines { lines ->
lines.forEach(::println)
}
注:
txt文件应该在您的类路径中(例如,在src/main/resources目录中) 上述解决方案都默认将文件编码处理为UTF-8。您可以指定所需的编码作为函数的参数。 上述解决方案不需要任何进一步的操作,如关闭文件或读取器。它们由Kotlin标准库自动处理。
我最喜欢的从BufferedReader输入读取整个文本文件的方法是:
字符串文本= input.lines().collect(collections .joining(System.lineSeparator())));
这将通过在每行后面添加新行(lineSeparator)来读取整个文件。如果没有分隔符,它会把所有的行连为一体。 这似乎从Java 8开始就存在了。
try {
File f = new File("filename.txt");
Scanner r = new Scanner(f);
while (r.hasNextLine()) {
String data = r.nextLine();
JOptionPane.showMessageDialog(data);
}
r.close();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog("Error occurred");
ex.printStackTrace();
}
import java.util.stream.Stream;
import java.nio.file.*;
import java.io.*;
class ReadFile {
public static void main(String[] args) {
String filename = "Test.txt";
try(Stream<String> stream = Files.lines(Paths.get(filename))) {
stream.forEach(System.out:: println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
只需使用java 8流。
Cactoos提供了一个声明性的一行代码:
new TextOf(new File("a.txt")).asString();