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.