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

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

问题描述

我想运行一个 java 类,参数以文件形式提供.

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

在外壳上,我可以做到

    java SomeClass < 1.txt

intellij 和/或 gradle 上是否有与此等效的内容.

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

我尝试了 IntelliJ IDEA -> 编辑配置.但是,争论没有通过.

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

推荐答案

更新:

此功能现在可用于某些运行/调试配置.目前基于 Java 的运行配置支持的类型有:Application、Java Scratch、JUnit、JarApplication.

This feature is now available for some Run/Debug configurations. At the moment supported types for Java-based run configurations are: Application, Java Scratch, JUnit, JarApplication.

使用重定向输入选项:

2017 年的原始答案以及解决方法:

Original answer from 2017 with the workaround:

IntelliJ IDEA 目前不支持:

IntelliJ IDEA doesn't support it at the moment:

  • IDEA-88717 无法在 Run/配置从文件读取 STDIN调试配置
  • IDEA-88717 No way to configure STDIN reading from a file at Run/Debug configurations

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

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);
  }
}

确保指定文件的完整路径或将 IntelliJ IDEA 运行/调试配置中的工作目录更改为 1.txt 的位置.

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.

现在您可以运行 MainWrapper 类而不是 Main 类,它的工作方式与运行相同

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

java Main < 1.txt

如果需要用不同的文件名进行测试,将new File("1.txt")替换为args[0],并在args[0]中传递文件名code>MainWrapper 运行/调试配置 程序参数 字段.

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天全站免登陆