在Java中,似乎有不同的方式来读取和写入文件数据。
我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?
在Java中,似乎有不同的方式来读取和写入文件数据。
我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?
当前回答
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流。
其他回答
到目前为止,我还没有在其他答案中看到它。但是如果“最佳”意味着速度,那么新的Java I/O (NIO)可能提供最快的性能,但对于初学者来说并不总是最容易理解的。
http://download.oracle.com/javase/tutorial/essential/io/file.html
这里有另一种不使用外部库的方法:
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;
}
你可以使用readAllLines和join方法在一行中获取整个文件内容:
String str = String.join("\n",Files.readAllLines(Paths.get("e:\\text.txt")));
它默认使用UTF-8编码,可以正确读取ASCII数据。
你也可以使用readAllBytes:
String str = new String(Files.readAllBytes(Paths.get("e:\\text.txt")), StandardCharsets.UTF_8);
我认为readAllBytes更快更精确,因为它不会用\n替换新行,也不会用\r\n替换新行。哪一种合适取决于你的需要。
Guava提供了一个简单的例子:
import com.google.common.base.Charsets;
import com.google.common.io.Files;
String contents = Files.toString(filePath, Charsets.UTF_8);
我编写的这段代码对于非常大的文件要快得多:
public String readDoc(File f) {
String text = "";
int read, N = 1024 * 1024;
char[] buffer = new char[N];
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while(true) {
read = br.read(buffer, 0, N);
text += new String(buffer, 0, read);
if(read < N) {
break;
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
return text;
}