I have this code:
import java.util.*;
import java.io.*;
public class ArrayListUse {
public static void main(String[] args) {
if (args.length != 1) {
System.err.print("You must specify an argument: filename");
System.exit(0);
}
File fd = new File(args[0]);
Scanner file = null;
// Creating ArrayList object
ArrayList<String> list = new ArrayList();
try {
file = new Scanner(fd);
}
catch (FileNotFoundException e) {
System.err.println("File does not exists " + e.getMessage());
System.exit(0);
}
// Reading file, adding lines to the list
while (file.hasNext()) {
// TO COMPLETE ...
list.add(file.nextLine());
}
file.close();
// Sorting the list, writing it to console
Collections.sort(list);
//Print
System.out.println(list.toString());
}
}
The code takes a file passed to main, creates an instance of the class ArrayList<E>
of type String (list), reads the content of the file line by line and dumps it into list
, then sorts it using the sort
class method java.util.Collections
and finally prints it on the screen .
What I don't understand is how I pass the file to main. I have read that I can pass parameters every time I call the method from the cmd but every time I run it it tells me that it does not exist, even though I have compiled with javac and not with bluej. I leave a catch.
There are several parts I'd like to point out in order to understand the purpose of your question and then indicate possible outcomes.
In the first condition you ask for the main's own args, enter that condition and "force" the program to close. Because? Your program will end right there.
After that
File fd = new File(args[0]);
, once again referencing the main itself. I don't know if the purpose ofString[] args
the main itself is understood, it is interesting to look for it and I would like to ignore it so as not to make this very long.I like to complain so let's take the opportunity to indicate what to put
Scanner file = null;
for two lines laterfile = new Scanner(fd);
, save and put in a single line. Apart from moving the structure of the try catch.To finish you use
System.exit(0);
in the catch, but when it is indicated it0
means that the execution went well. Is that purpose wanted or is it better to indicate that it is not, since the file cannot be found?And in this way it should work for you when you indicate the route well or if you don't, the catch will be executed as it should.
I understand that you will execute through the CMD and pass the values through the command line, but for a file you should indicate it with another type, so using the
args
as if it had something was wrong.I hope it helps.