Run Program from IntelliJ with Command Line File Input

后端 未结 6 412
青春惊慌失措
青春惊慌失措 2020-12-19 07:34

I am running OSX 10.11 with IntelliJ 14.1.15.

I have a programme which takes a txt file as an argument. I can run it from the terminal through java Searc

相关标签:
6条回答
  • 2020-12-19 08:16

    Adding the input file name's relative path in the "Program Arguments" will allow the "main" method reading the argument in as a "String"

    However, in order to actually let the System to understand using data from the file as standard input, it seems we have to specifically read the file and set the input stream as the system input :

        try {
            FileInputStream inputStream = new FileInputStream(new File(args[0]));
            System.setIn(inputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    
    0 讨论(0)
  • 2020-12-19 08:17

    You need to go in the menu Run -> Edit configurations.

    Select your configuration and add the parameters in the field Program arguments

    The field Program arguments is what appears after the class name from command line. For example:

    java MyMainClass ProgramArgument1 ProgramArgument2 ProgramArgument3
    

    in your example

    java SearchCmd test.txt
    

    the program argument is test.txt

    Note: Use an absolute path or check that the working directory is the directory containing your file

    0 讨论(0)
  • 2020-12-19 08:18

    Go to Run -> Edit Configurations, Select Application, then give the main class name and program arguments. Then Run.

    0 讨论(0)
  • 2020-12-19 08:18

    I just figured it out.

    So instead of pasting in an absolute path, you need to paste a relative path from the root directory of your IntelliJ project. And most importantly you have to ommit the initial forward slash.

    So my absolute path to the file might be this: Computer/project/TestInput/itcwww-small.txt

    But the path that I need to put into Programme Arguments is: TestInput/itcwww-small.txt

    I hope that this will help someone else.

    0 讨论(0)
  • 2020-12-19 08:27

    Steps to follow-
    1. Run->Edit Configurations.


    2. Select Application.



    3. Provide main class name and command line arguments and apply.

    4. Run

    0 讨论(0)
  • 2020-12-19 08:31

    I had the same issue and was very confused with the previous answers of this question, so here is my explanation to anyone that is lost like I was.

    With the project open.

    Run > Edit Configurations....

    Add the whole directory that the file is in it on the Program Arguments field with the file format at the end.

    0 讨论(0)
提交回复
热议问题