Я всегда использую этот метод, чтобы легко прочитать содержимое файла. Это достаточно эффективно? 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(); }
Я всегда смотрю в FileUtils http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html, чтобы узнать, есть ли у них метод. В этом случае я бы использовал readFileToString (File) http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#readFileToString%28java.io.File%29
Они уже рассмотрели почти все проблемные случаи ...
Вы можете обнаружить, что это достаточно быстро.
String text = FileUtils.readFileToString(file);
AFAIK, по умолчанию используется размер буфера 8K. Однако я обнаружил, что большие размеры, такие как 64 КБ, могут иметь небольшое значение.
Попробуйте следующее, оно должно работать (хорошо):
public static String read(File file) { StringBuilder str = new StringBuilder(); BufferedReader in = null; String line = null; try { in = new BufferedReader(new FileReader(file)); while ((line = in.readLine()) != null) str.append(line); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return str.toString(); }