Java file input as command line argument

2019-05-18 16:11发布

How do you process information in Java that was input from a file. For Example: suppose you have a file input.txt. The contents of this file is: abcdefghizzzzjklmnop azzbcdefghijklmnop

My hope would be that the information would be put into the argument array of strings such that the following code would output "abcdefghizzzzjklmnop"

class Test {
    public static void main(String[] args) {
        System.out.println(args[0]);
    }
}

The command I have been using throws an array out of bound exception. This command is:

java Test < input.txt

Non-file based arguments work fine though. ie. java Test hello,a nd java Test < input.txt hello.

More information: I have tried putting the file contents all on one line to see if \n \r characters may be messing things up. That didn't seem to help.

Also, I can't use the bufferedreader class for this because this is for a program for school, and it has to work with my professors shell script. He went over this during class, but I didn't write it down (or I can't find it).

Any help?

3条回答
再贱就再见
2楼-- · 2019-05-18 16:34

You should be able to read the input data from System.in.

Here's some quick-and-dirty example code. javac Test.java; java Test < Test.java:

class Test
{
    public static void main (String[] args)
    {
        byte[] bytes = new byte[1024];
        try
        {
            while (System.in.available() > 0)
            {
                int read = System.in.read (bytes, 0, 1024);
                System.out.write (bytes, 0, read);
            }
        } catch (Exception e)
        {
            e.printStackTrace ();
        }
    }
}
查看更多
3楼-- · 2019-05-18 16:40

I'm not sure why you want to pass the contents of a file as command line arguments unless you're doing some weird testbed.

You could write a script that would read your file, generate a temporary script in which the java command is followed by your needs.

查看更多
对你真心纯属浪费
4楼-- · 2019-05-18 16:50

It seems any time you post a formal question about your problem, you figure it out.

Inputing a file via "< input.txt" inputs it as user input rather than as a command line argument. I realized this shortly after I explained why the bufferedreader class wouldn't work.

Turns out you have to use the buffered reader class.

查看更多
登录 后发表回答