我一直在互联网上查找,试图找出读取不太长的文本文件的最佳方法(这里的用例涉及小型 OpenGL 着色器)。我最终得到了这个:
private static String load(final String path)
{
String text = null;
try
{
final FileReader fileReader = new FileReader(path);
fileReader.read(CharBuffer.wrap(text));
// ...
}
catch(IOException e)
{
e.printStackTrace();
}
return text;
}
在什么情况下这部分代码会导致效率低下?这是 CharBuffer.wrap(text)
一件好事吗?
最佳答案
如果你想逐行读取文件:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
如果您想一次性阅读完整文件:
String text=new String(Files.readAllBytes(...)) 或 Files.readAllLines(...)
关于java - 这是读取文本文件的好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35347766/