IntelliJ IDEA:使用外部文件的args运行java [英] IntelliJ IDEA: Run java with args from external file

查看:372
本文介绍了IntelliJ IDEA:使用外部文件的args运行java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在shell上,我可以做

  java SomeClass< 1.txt 

这对intellij和/或gradle是否有任何等价物。



我尝试了IntelliJ IDEA - >编辑配置。但是,该参数没有被传递。

解决方案

IntelliJ IDEA目前不支持:




  • IDEA-88717 无法在运行/调试配置中配置STDIN从文件读取



您可以调整代码,使其接受文件名作为参数并将其打开以供阅读。或者你可以创建一个包装类来重新定义 System.in ,然后开始你的原始 Main 类:

  import java.io.File; 
import java.io.FileInputStream;
import java.io.IOException;
$ b $ public class MainWrapper {
public static void main(String [] args)throws IOException {
FileInputStream is = new FileInputStream(new File(1.txt));
System.setIn(is);
Main.main(args);




$ b $ p $请确保指定文件的完整路径或将IntelliJ IDEA Run / Debug配置中的工作目录更改为 1.txt



位置你可以运行 MainWrapper 类而不是 Main 类,它的运行方式与运行相同。
$ b

  java Main< 1.txt 

如果您需要使用不同的文件名进行测试,请将 new使用 args [0] 将文件(1.txt)传递给 MainWrapper 运行/调试配置程序参数字段。


I want to run a java class with args supplied as a file.

On shell, i can do

    java SomeClass < 1.txt

Is there any equivalent for this on intellij and/or gradle.

I tried on IntelliJ IDEA -> edit configurations. But, the argument is not getting passed.

解决方案

IntelliJ IDEA doesn't support it at the moment:

  • IDEA-88717 No way to configure STDIN reading from a file at Run/Debug configurations

You can adjust the code so that it accepts the file name as a parameter and opens it for reading. Or you can create a wrapper class that will redefine System.in, then start your original Main class:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class MainWrapper {
  public static void main(String[] args) throws IOException {
    FileInputStream is = new FileInputStream(new File("1.txt"));
    System.setIn(is);
    Main.main(args);
  }
}

Make sure to either specify the full path to the file or to change the working directory in IntelliJ IDEA Run/Debug configuration to the location of 1.txt.

Now you can run MainWrapper class instead of the Main class and it will work the same as running

java Main < 1.txt

If you need to test with different file names, replace new File("1.txt") with args[0] and pass the file name in the MainWrapper Run/Debug configuration Program arguments field.

这篇关于IntelliJ IDEA:使用外部文件的args运行java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆