Java read whole file into string
July 15, 2011 13:25:45 Last update: July 15, 2011 13:25:45
Read the whole contents of a file into a String. It's better to read the whole file as bytes and convert to String than to read the file line by line and concatenate the lines.
Using
String getFileContents(String fileName) throws Exception { File theFile = new File(fileName); byte[] bytes = new byte[(int) theFile.length()]; InputStream in = new FileInputStream(theFile); int m = 0, n = 0; while (m < bytes.length) { n = in.read(bytes, m, bytes.length - m); m += n; } in.close(); // using default encoding, this is probably what BufferedReader.readLine does anyway return new String(bytes); }
Using
java.nio:
import java.io.FileInputStream; import java.nio.channels.FileChannel; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; public class ReadWholeFile2 { public static void main(String[] args) throws Exception { String contents = getFileContents("test.txt"); System.out.println(contents); } static String getFileContents(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); FileChannel fch = fin.getChannel(); // map the contents of the file into ByteBuffer ByteBuffer byteBuff = fch.map(FileChannel.MapMode.READ_ONLY, 0, fch.size()); // convert ByteBuffer to CharBuffer // CharBuffer chBuff = Charset.defaultCharset().decode(byteBuff); CharBuffer chBuff = Charset.forName("UTF-8").decode(byteBuff); return chBuff.toString(); } }