Hey all I'm fairly new to this but I want to not hardcode a file to be read in but I want to read it in from the terminal/command prompt. Here is what I have so far, I'm hardcoding the filename in bufferedWriter but how can I make it to where I can do a command such as (java main < in.txt > out.txt). Thanks in advance.
public static void main(String[] args) {
String inFile = "in.txt";
String outFile = "out.txt";
if (args.length > 1) {
inFile = args[0];
outFile = args[1];
}
Lexer lexer = new Lexer(inFile);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
Token t;
while ((t = lexer.nextToken()) != null) {
writer.write(t.toString());
writer.newLine();
}
writer.close();
System.out.println("Done tokenizing file: " + inFile);
System.out.println("Output written in file: " + outFile);
} catch (IOException e) {
e.printStackTrace();
}
}
You don't, the OS handles the IO redirection with java main < in.txt > out.txt
. Instead you read from System.in
and write to System.out
. Alternatively , based on the code you posted you might run it with
java main in.txt out.txt
Then your program would receive "in.txt"
as args[0]
and "out.txt"
as args[1]
.
Read from System.in
and write to System.out
- also remember anything you write to System.out
will be written to the file. such as Done tokenizing file: + inFile
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.