Ubuntu: Redirection from a .txt file in Java
This should be pretty simple but for some reason, I can't get this program to take arguments from a .txt file and output it. Here's my code:
public class Lab2 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Lab2_CLA.Lab2_CLA(args);
}
}
public class Lab2_CLA {
public static void Lab2_CLA(String[] data)
{
System.out.printf("%s, %s: %s%n", data[1], data[0], data[2]);
}
}
I compiled the code and开发者_如何学运维 it works if I give it arguments through the terminal. Ex:
Typing "java lab2/Lab2 John Doe 12345678"
Prints out: "Doe, John: 12345678"
However, how can I get it to read data from a .txt file by typing the following into the terminal: "java lab2/Lab2 < input.txt"? Whenever I do this, I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at lab2.Lab2_CLA.Lab2_CLA(Lab2_CLA.java:12)
at lab2.Lab2.main(Lab2.java:34)
Input redirection sends the file to the program's stdin (standard input file), not in its command line parameters. On a Unix-alike you can obtain the effect you want by using the backtick operator:
java lab2/Lab2 `cat input.txt`
In short, the text between the backticks is executed, and the result of the execution will be inserted in its place.
EDIT (responding to OP's edit):
You get an out of bounds exception because with the redirection the program doesn't get any command line parameters, yet hard-address elements 0 1 and 2 of the args array.
Should for some reason the backtick based solution not be possible for you the only option will be to modify your program to either read its stdin (technique show here Java file input as command line argument), or accept a filename as an argument, and read that file.
精彩评论