Java convert file data to String example

private static String readFileToString(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();
        System.out.println(fileData.toString());
        return fileData.toString();
    }

-- OR --

Download from apache commons FileUtils class (General file manipulation utilities)

readFileToString

public static String readFileToString(File file,
                                      String encoding)
                               throws IOException
Reads the contents of a file into a String. The file is always closed.
Parameters:
file - the file to read, must not be null
encoding - the encoding to use, null means platform default
Returns:
the file contents, never null
Throws:
IOException - in case of an I/O error
UnsupportedEncodingException - if the encoding is not supported by the VM

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.