-1

As I am new here and I have search some questions but not able to full fill my requirement, so please help me for this.

How can I allow user to enter the path of file as command line argument and then I can read the content of file and display from that file,

Also If file is not there then it should display appropriate message for that.

Please help me for this as I am new to tech and site both.

Harprit Kaur
  • 21
  • 1
  • 6
  • Welcome to SO.com, this is not a website to ask question without trying yourself. You should ask your self three questions. And look them up one by one on the internet. How can I read user input? How can I check a file exist? How can I read the file contents? Use a `Scanner` for input and a [`InputStream`](https://docs.oracle.com/javase/tutorial/essential/io/file.html) to open file. – martijnn2008 Nov 12 '16 at 11:10
  • You cave asked a number of different questions: 1) how to read command line argument 2) how to open a file, 3) how to read a file, 4) how to display data, 5) how to deal with a file that cannot be opened, 6) how to write an error message. Research each of these separate, and then (if you can't) find any answers in your research, ask >>separate<< questions. – Stephen C Nov 12 '16 at 11:59
  • *"I have search some questions but not able to full fill my requirement"* - That's right. If you search for code that does all of those things you are unlikely to find what you want. Instead, search for answers to the individual questions, and then use that knowledge to WRITE a program. – Stephen C Nov 12 '16 at 12:02

1 Answers1

0

Here is the Program of Reading the file from Command Line Argument

import java.io.*;
class MyFileReader
{
    public static void main(String args[])
    {
        try
        {
            FileInputStream fr=new FileInputStream(new File(args[0]));
            int i=0;
            while((i=fr.read())!=-1)
            {
                System.out.print((char)i);
            }
            fr.close();
        }
        catch(ArrayIndexOutOfBoundsException ex)
        {
            System.out.println("\nPlease Enter the File Name in Command Line Argument. \n"+
            "For Example :- java MyFileReader C:\\Users\\Desktop\\File1.txt");
        }
        catch(IOException ex)
        {
                System.out.println("File Does Not Found in given Directory. ");
        }
    }
}
nss8889
  • 1
  • 1