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

Snippets has posted 5883 posts at DZone. View Full User Profile

Java - To Read A File Into A String

02.01.2006
| 502802 views |
  • submit to reddit
        // 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

Abdel Zoo replied on Wed, 2014/10/22 - 8:14pm

  Thank you for your sweet topic     العاب كرتون نتورك

Snippets Manager replied on Thu, 2010/10/07 - 10:33am

Why would a BufferedInputStream speed it up if you're only issuing one read, and it's for the length of the entire file?

Andrew Spencer replied on Wed, 2010/07/21 - 4:44am

In reply to the last comment, don't forget to close the input stream, otherwise you'll have a resource leak: 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 - 7:57pm

Yes, you can use f.read(). As the API says: If no byte is available because the stream is at the end of the file, the value -1 is returned; (...) Take a look at the while: (...) while((numRead=reader.read(buf)) != -1){ (...) The usage is correct.

Snippets Manager replied on Wed, 2011/04/20 - 10:34am

You cannot use f.read(). Read this: http://www.coderanch.com/how-to/java/ReadDoesntDoWhatYouThinkItDoes

a b replied on Sat, 2010/01/02 - 10:31pm

In replay to the last comment. I suggest you throw it in a BufferedInputStream to speed it up. 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 - 5:27pm

Hi! I saw your post and finally found another solution... Why don't just use something like that: 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 - 6:38am

Thanks! but efficiency could be easily improved: /** @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 - 2:19pm

See also my snippet.