- A Concurrent Affair - https://www.concurrentaffair.org -

Input/Output Redirection in DrJava?

On the AP Computer Science mailing list, there was a teacher who wanted to do input/output redirection and who asked why the following didn’t work:

java LetterCounter < input.txt

The Interactions Pane in DrJava is not a DOS command line or Unix-type shell, and it does not support I/O redirection.

The java MyClass arg0 arg1 arg2 thing is only "syntactic sugar" for

1
MyClass.main(new String[] {"arg0", "arg1", "arg2"})

While the Interactions Pane doesn't support I/O redirection and piping with <, > and |, it is a fully functional Java interpreter.

You can, therefore, create a FileInputStream and use it as System.in before starting your program.

For example, if my program is the following:

1
2
3
4
5
6
7
8
9
10
11
import java.io.*;

public class ReadFromStdIn {
  public static void main(String [1][] args) throws IOException [2] {
    BufferedReader [3] br = new BufferedReader [3](new InputStreamReader [4](System [5].in));
    String [1] line;
    while((line = br.readLine()) != null) {
      System [5].out.println(line);
    }
  }
}

Then I can start it the following way in DrJava to make it read from the test.txt file on my desktop:

1
2
3
4
5
6
7
8
9
Welcome to DrJava.  Working directory is C:\Users\mgricken\Documents\Dev\Java
> import java.io.FileInputStream
> System [5].setIn(new FileInputStream [6]("C:/Users/mgricken/Desktop/test.txt"))
> java ReadFromStdIn
Foo
Bar
Fuzz
Bam
>

The four lines with "Foo Bar Fuzz Bam" are coming from the test.txt file.

I realize that this is different from how Java programs are started in DOS or Unix shells, but it's only because the main method is a very special method. DrJava's Interaction Pane becomes elegant because you can run any method.

I could write the program this way, for example:

1
2
3
4
5
6
7
8
9
10
11
import java.io.*;

public class ReadFromStream {
  public void readFromStream(InputStream [7] is) throws IOException [2] {
    BufferedReader [3] br = new BufferedReader [3](new InputStreamReader [4](is));
    String [1] line;
    while((line = br.readLine()) != null) {
      System [5].out.println(line);
    }
  }
}

Then I could run the program in the following ways:

1
2
3
4
5
6
7
8
Welcome to DrJava.  Working directory is C:\Users\mgricken\Documents\Dev\Java
> import java.io.FileInputStream
>
> // read from standard in
> new ReadFromStream().readFromStream(System [5].in)
>
> // read from test.txt
> new ReadFromStream().readFromStream(new FileInputStream [6]("C:/Users/mgricken/Desktop/test.txt"))

I generally advise to do as little processing in the main method and rely as little as possible on magic like "where is my standard in coming from?", and to write as much general purpose code as possible like the readFromStream() method. It will make code more reusable and work better in DrJava's Interaction Pane.

I hope this helps. Thanks for using DrJava!

[8] [9]Share [10]