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+"TestRead.java";
 
		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 = reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
			buf = new char[1024];
		}
 
		reader.close();
 
		String returnStr = fileData.toString();
		System.out.println(returnStr);
		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  
  • kai ran

    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