There are many alternatives for doing this. A higher level thing could be using a Scanner
class. I assume, since you are learning java, you might have come across Scanner
class for reading the input from console. You can use the Scanner
same way to read the file also.
You can use Scanner#nextInt()
, Scanner#next()
, etc... methods for reading the input. You can use args[]
array for taking the command line arguments.
Since, you haven't mention exactly what kind of way your data is stored in file, it's hard to give a working example.
import java.util.Scanner;
public class Tester {
public static void main(String args[]) {
if (args.length > 0) {
Scanner sc = new Scanner(new File(args[0]));
//use here the functions such as sc.nextInt() and so on
}
}
}
Link to the docs: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
If you are reading big file in java (see my answer to other question): file size too big for java:
Working Example:
This program prints the file contents to console.
Execute this program using java Tester yourFileName
after compilation.
import java.util.*;
import java.io.*;
public class Tester {
public static void main(String args[]) {
try {
if (args.length > 0) {
Scanner sc = new Scanner(new File(args[0]));
while (sc.hasNext()) {
System.out.println(sc.next());
}
} else {
System.out.println("No file name given");
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
}
}