Create a Java program to read a file with Eclipse

Below is a very simple java program uses to read the content of a file. I am writing this program with Eclipse so before I run the program I need to go through Run->Run Configurations and enter the filepath into the Program arguments box like below.

next click the run button
next click the run button
package com.gadgetscode.java;

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

public class ReadIO {

	public static void main(String[] args) {
		
		if (args.length == 0) {
			System.err.println("usage: java ReadIO stdinfile");
			return;
		}
		try {
			System.setIn(new FileInputStream(args[0]));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		int ch;
		try {
			while ((ch = System.in.read()) != -1)
				System.out.print((char) ch);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

The above program will create the below output…

hello there
are you good?
thank you!

Like this post? Kindly share!

  • Charli Xavier

    Hello!
    This is a good article because there are many tips and also many advices that will be very useful to me.
    Thanks!
    http://www.baloune.com