Read file write String

Below java code could be use to read files and write stream to string. For this java API BufferedInputStream has been used:

package com.fileio;

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

public class ReadFileToString {
	public static void main(String[] args) {

		// create file object
		File file = new File("C:\\JavaHorn\\Test Files\\Test.txt");
		BufferedInputStream bin = null;

		try {
			// create FileInputStream object
			FileInputStream fin = new FileInputStream(file);

			// create object of BufferedInputStream
			bin = new BufferedInputStream(fin);

			// create a byte array
			byte[] contents = new byte[1024];

			int bytesRead = 0;
			String strFileContents;

			while ((bytesRead = bin.read(contents)) != -1) {

				strFileContents = new String(contents, 0, bytesRead);
				System.out.print(strFileContents);
			}

		} catch (FileNotFoundException e) {
			System.out.println(e);
		} catch (IOException ioe) {
			System.out.println(ioe);
		} finally {
			try {
				if (bin != null)
					bin.close();
			} catch (IOException ioe) {
				System.out.println(ioe);
			}

		}
	}
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *