Java Code – Convert a file to a String

How to read file content into a string?

The following is the Java code to do that. To make it work, the filePath need to be changed.

public static String readFileToString() throws IOException {
		File dirs = new File(".");
		String filePath = dirs.getCanonicalPath() + File.separator+"src"+File.separator+"";
		StringBuilder fileData = new StringBuilder(1000);//Constructs a string buffer with no characters in it and the specified initial capacity
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			buf = new char[1024];
		String returnStr = fileData.toString();
		return returnStr;

By saying String, it is not exactly correct, it is actually called a StringBuffer in Java. Here is a post about Java String's immutability. StringBuffer and StringBuilder are similar and they both are are for mutable strings. But StringBuffer is safe for use by multiple threads. The reason to use StringBuilder instead of StringBuffer here is that StringBuilder is faster, as it performs no synchronization.

From programming usage perspective, String, StringBuffer, StringBuilder are all strings.

Category >> Real Methods  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. kai ran on 2013-11-25

    In the while loop, each line is read, we have to recreate new char array, that seams a lot of resource consumption if the file is big

  2. Sourav Kundu on 2016-7-4

    After copying the characters from array (buf) to string, we can make all characters to buffer as ”, in such a way we do not need to allocate these space any more.
    And moreover, we can do fileData.append(buf.toString());
    for (int i=0;i<1024;++i) buf[i]='';
    Please comment.

Leave a comment