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.


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

package com.codingnous.tutorial;

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 = != -1) {
			// Print ASCII value of char.
			System.out.print((char) i);

		// Take input user input from console.
		Scanner s = new Scanner(;
		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
		System.out.println("String written to text file.");



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.