java需要帮助来提高代码的效率
我总是使用这种方法来轻松地读取文件的内容。它足够有效吗?1024适合缓冲区大小吗
public static String read(File file) {
FileInputStream stream = null;
StringBuilder str = new StringBuilder();
try {
stream = new FileInputStream(file);
} catch (FileNotFoundException e) {
}
FileChannel channel = stream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
while (channel.read(buffer) != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
str.append((char) buffer.get());
}
buffer.rewind();
}
} catch (IOException e) {
} finally {
try {
channel.close();
stream.close();
} catch (IOException e) {
}
}
return str.toString();
}
# 1 楼答案
你可能会发现这已经足够快了
好的,这使用默认的缓冲区大小8K。然而,我发现更大的尺寸,比如64K,可能会有轻微的不同
# 2 楼答案
我总是查看FileUtilshttp://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html,看看它们是否有方法。在本例中,我将使用readFileToString(文件) http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#readFileToString%28java.io.File%29
他们已经处理了几乎所有的问题案件
# 3 楼答案
试试下面的方法,它应该很有效: