views:

7084

answers:

3

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?

+5  A: 

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 ();
     }
    }
}
John Millikin
Yep, problem solved. Thanks.
A: 

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.

A: 

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.

Uri
He's a bit confused; apparently his professor wrote a script that writes a file to his app's stdin, and he thinks it's a special form of command-line parameter.
John Millikin