No announcement
 

File Input and Output

Apart from taking user defined input via console, we can also take input from files and write output to files as well.

Example:

For the below example make sure file "D:\SampleInput.txt" is created, and have few lines of text in it.

FileInputOutputDemo.java

package com.codingnous.tutorial;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class FileInputOutputDemo {

	public static void main(String[] args) throws IOException {

		// FileInputStream object with file path as constructor argument.
		FileInputStream fi = new FileInputStream("D:\\SampleInput.txt");

		int i;

		// Read char value one by one until no char is left.
		while ((i = fi.read()) != -1) {
			// Print ASCII value of char.
			System.out.print((char) i);
		}

		// Take input user input from console.
		Scanner s = new Scanner(System.in);
		System.out.print("\nEnter string to write to file: ");
		String output = s.nextLine();

		// Convert input string to byte array.
		byte[] b = output.getBytes();

		// FileOutputStream object.
		FileOutputStream fo = new FileOutputStream("D:\\SampleOutput.txt");
		
		// Write the byte array to file
		fo.write(b);
		
		fo.close();
		System.out.println("String written to text file.");

	}

}

Output
This message comes from text file. Enter string to write to file: This message will be written in output text file. String written to text file.