Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

IntelliJ IDEA: Run java with args from external file

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UPDATE:

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.

Use the Redirect input from option:

Redirect input from


Original answer from 2017 with the workaround:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...