[英]How can I read a text file from the terminal and save the output to another file in java?
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). 到目前为止,这是我要的东西,我正在bufferedWriter中对文件名进行硬编码,但是如何将其命名为可以执行命令的地方,例如(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
. 你不这样做,操作系统处理与IO重定向java main < in.txt > out.txt
。 Instead you read from System.in
and write to System.out
. 相反,您从System.in
读取并写入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]
. 然后您的程序将以args[0]
形式接收"in.txt"
,以args[1]
形式接收"in.txt"
"out.txt"
。
Read from System.in
and write to System.out
- also remember anything you write to System.out
will be written to the file. 从System.in
读取并写入System.out
还记得您写入System.out
都会写入该文件。 such as Done tokenizing file: + inFile
例如Done tokenizing file: + inFile
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.