DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Java - To Read A File Into A String
// description of your code here //This function reads the given filename into a string. Path handling is not too good and buffer sizes are hardcoded right now.
/** @param filePath the name of the file to open. Not sure if it can accept URLs or just filenames. Path handling could be better, and buffer sizes are hardcoded */ private static String readFileAsString(String filePath) throws java.io.IOException{ StringBuffer fileData = new StringBuffer(1000); BufferedReader reader = new BufferedReader( new FileReader(filePath)); char[] buf = new char[1024]; int numRead=0; while((numRead=reader.read(buf)) != -1){ String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); return fileData.toString(); } // insert code here..
Comments
Snippets Manager replied on Thu, 2010/10/07 - 9:33am
Andrew Spencer replied on Wed, 2010/07/21 - 3:44am
private static String readFileAsString(String filePath) throws java.io.IOException{ byte[] buffer = new byte[(int) new File(filePath).length()]; BufferedInputStream f = null; try { f = new BufferedInputStream(new FileInputStream(filePath)); f.read(buffer); } finally { if (f != null) try { f.close(); } catch (IOException ignored) { } } return new String(buffer); }
Snippets Manager replied on Mon, 2011/05/16 - 6:57pm
(...) while((numRead=reader.read(buf)) != -1){ (...)
The usage is correct.Snippets Manager replied on Wed, 2011/04/20 - 9:34am
a b replied on Sat, 2010/01/02 - 9:31pm
private static String readFileAsString(String filePath) throws java.io.IOException{ byte[] buffer = new byte[(int) new File(filePath).length()]; BufferedInputStream f = new BufferedInputStream(new FileInputStream(filePath)); f.read(buffer); return new String(buffer); }
Snippets Manager replied on Mon, 2009/11/02 - 4:27pm
private static String readFileAsString(String filePath) throws java.io.IOException{ byte[] buffer = new byte[(int) new File(filePath).length()]; FileInputStream f = new FileInputStream(filePath); f.read(buffer); return new String(buffer); }
Snippets Manager replied on Sun, 2007/06/10 - 5:38am
/** @param filePath the name of the file to open. Not sure if it can accept URLs or just filenames. Path handling could be better, and buffer sizes are hardcoded */ private static String readFileAsString(String filePath) throws java.io.IOException{ StringBuffer fileData = new StringBuffer(1000); BufferedReader reader = new BufferedReader( new FileReader(filePath)); char[] buf = new char[1024]; int numRead=0; while((numRead=reader.read(buf)) != -1){ fileData.append(buf, 0, numRead); } reader.close(); return fileData.toString(); }
Also remember to use StringBuilder instead of StringBuffer in Java 5.0.Snippets Manager replied on Mon, 2012/05/07 - 1:19pm