[英]Input file for JAR
I want to send the input of a jar from one file and save the output in another,我想从一个文件发送一个 jar 的输入并将输出保存在另一个文件中,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> builder = new ArrayList<>();
String line;
while (!(line = sc.nextLine()).isBlank()) {
builder.add(line);
}
builder.stream().sorted().forEach(System.out::println);
sc.close();
}
when I execute the jar I try it like this当我执行 jar 时,我会像这样尝试
java -jar name.jar > output.txt < input.txt
but it generates the exception java.util.NoSuchElementException, I appreciate any help.但它会生成异常 java.util.NoSuchElementException,感谢您的帮助。
This is what I believe is the easiest way to accomplish what you are trying to do:这是我认为完成您正在尝试做的事情的最简单方法:
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("output.txt"); // Used to write to output.txt
Scanner sc = new Scanner(System.in);
List<String> builder = new ArrayList<>();
while (sc.hasNextLine()) { // Same thing as what you had, just 1 less line
// Not entirely sure what you're trying to do here;
//if no input is given at the EXACT time the program is run, this will be skipped
builder.add(sc.next());
}
builder.stream().sorted().forEach((s) -> { // Changed this to a lambda
System.out.println(s);
try {
fw.write(s);
} catch (IOException e) {
e.printStackTrace();
}
});
fw.close();
sc.close();
}
The easiest way would be to pass your input.txt
file as a parameter to your jar.最简单的方法是将
input.txt
文件作为参数传递给 jar。 You can then utilize Files.readAllLines
to read your text file and do your sort and then send each line to std out
然后,您可以利用
Files.readAllLines
读取您的文本文件并进行排序,然后将每一行发送到std out
Then you can redirect std out
to your output.txt
file.然后你可以将
std out
重定向到你的output.txt
文件。
public static void main(String[] args) throws IOException {
if (args == null || args.length == 0) throw new RuntimeException("No file provided");
Path file = Paths.get(args[0]);
if (Files.notExists(file)) throw new IOException(args[0] + " cannot be found.");
Files.readAllLines(file).stream().sorted().forEach(System.out::println);
}
Then you can invoke it like this:然后你可以像这样调用它:
java -jar name.jar input.txt > output.txt
The code is okay, not perfect, but it works.代码没问题,不完美,但可以工作。 Of course your class needs to have some more lines (like defining the import and class definition etc.), but you only posted the main method is and that's okay for me.
当然,您的类需要有更多行(例如定义导入和类定义等),但是您只发布了 main 方法,这对我来说没问题。
At runtime, you're piping < input.txt
as your standard input which is great.在运行时,您将
< input.txt
作为标准输入进行管道< input.txt
,这很棒。
I think your problem could be:我认为你的问题可能是:
input.txt
is in a different directory at runtime, so you're actually not piping anything as an input.input.txt
在运行时位于不同的目录中,因此您实际上没有将任何内容作为输入进行管道传输。 There's no error from the command line, but this way you get the exception too. One of those could be the cause.其中之一可能是原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.