How to Convert File Content to String in Java

Convert File Content to String in Java

In this example, We will show about, How to write simple program about Convert File Content to String in Java. The example were tested and shared in the post.

#1 File Content to String (Method 1)

package com.dineshkrish.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class FileToString1 {

	public static void main(String[] args) {
		
		// You can change it
		String fileName = "abc.txt";
		
		File file = new File(fileName);
		
		try {
			
			String content = "";
			
			FileInputStream fis = new FileInputStream(file);
			
			int data = fis.read();
			
			while(data != -1) {
				
				// Appending each character to String Object 
				content += ""+(char)data+"";
				
				data = fis.read();
			}
			
			fis.close();
			
			// Printing String Object
			System.out.println(content);
			
		} catch (FileNotFoundException e) {
			
			System.out.println(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		
	}
}

#2 File Content to String (Method 2)

package com.dineshkrish.io;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class FileToString2 {

	public static void main(String[] args) {

		String content = "";
		
		File file = new File("abc.txt");
		
		try {
			
			byte[] b = Files.readAllBytes(file.toPath());
			
			// Converting byte array to String
			content = new String(b);
			
		} catch (IOException e) {
			
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		
		// Printing String Object
		System.out.println(content);
		
	}
}

#3 File Content

Convert File Content to String in Java

#4 Final Output

———————————————–
Hello everyone,
Welcome to dineshkrish.com
———————————————–

References

1. Java IO Package JavaDocs
2. Java NIO Package JavaDocs

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.

  • Dinesh K

    Thanks for sharing.