1

So for an project, we need to have the program accept the file name to be read in from command line arguments of main method. That is, your program should be executable from the command line by calling:

~>java Project inputFile.txt

Which will output the modified contents of the file to the standard output.

But I am clueless on how to do this.

PS: We've covered how to use the command line arguments but not how to have a file read from this location. Any suggestions?

5377037
  • 9,493
  • 12
  • 43
  • 73
Ryan Dorman
  • 227
  • 1
  • 3
  • 10

4 Answers4

3

Say, you invoke your program as

java MyMainClass /path/to/file

Then in the main() method just use

File f = new File(args[0])

Then, you might want to validate that

f.exists()
f.isFile()
f.canRead()

etc.

To actually read the file you can follow those instructions as suggested in the comment by @Kevin Esche

Community
  • 1
  • 1
Adam Michalik
  • 9,448
  • 11
  • 55
  • 89
1
java MainClass <list of arguments>

Now in main class you will receive all the argument in String array, which is passed in the main method.

public static void main(String args[]) {
   for(String argument : args) {
     System.out.println(argument);
   }
}
YoungHobbit
  • 12,384
  • 9
  • 44
  • 70
  • as in the other answers: `So far, we've covered how to use the command line arguments but not how to have a file read from this location. Any suggestions?` – SomeJavaGuy Sep 10 '15 at 07:08
  • I would suggest you revise those class notes. Because all the answer saying what you already know. Please don't take it otherwise. Just a polite suggestion to you. – YoungHobbit Sep 10 '15 at 07:12
1

Maybe this would help, it reads and prints the file to the console.

public static void main(String[] args) {
    File f=  new File(arg[0]);

    InputStream is = new FileInputStream(f);

    int byteReaded;

    while ((byteReaded = is.read())!=-1) {
       System.out.print((char)byteReaded);

    }
}
Krzysztof Cichocki
  • 5,658
  • 1
  • 13
  • 31
1

When running a java program from the console you call:

java programName list of inputs separated by space

So in your case you have:

java Project inputFile.txt

When the JVM starts and calls main() it will take everything after your project name and create a String array of that separated by the spaces.

So in my first caommand line I would get:

{"list" + "of" + "inputs" + "separated" + "by" + "space"}

This string array will come into your program in the main function:

public static void main(String[] args) { ... }

Therefore, in your case, args[0] will be the file name you are looking for. You can then create a file reader of sorts. If you don't add any path to the front of the file name it will look for the file in the folder that your src folder is in.

Hope this helps.

Nicholas Robinson
  • 1,289
  • 1
  • 8
  • 18