3

If I have a simple java program that processes lines of text from standard input, then I can run it with the following script:

@Echo off
java Test < file.txt
pause
exit

The script redirects lines of input from file.txt into the java program.

Is there a way that I can avoid having to use a separate file? Or is this the easiest way?

Thanks.

3
  • Are you saying that you just want java to redirect your keyboard input to wherever? Commented May 2, 2010 at 15:08
  • I was wondering if there's a way to send multiple lines of input to the java program without using a file. Commented May 2, 2010 at 15:29
  • Can't you modify your Java main to read from args and just pass the file(s) in as parameter(s) to the main ? Commented May 2, 2010 at 16:01

2 Answers 2

4

Use a pipe.

This trivial Java app just prints out the lines from stdin:

public class Dump {
  public static void main(String[] args) {
    java.util.Scanner scanner = new java.util.Scanner(System.in);
    int line = 0;
    while (scanner.hasNextLine()) {
      System.out.format("%d: %s%n", line++, scanner.nextLine());
    }
  }
}

Invoked with this batch file:

@ECHO OFF
(ECHO This is line one
ECHO This is line two; the next is empty
ECHO.
ECHO This is line four)| java -cp bin Dump
PAUSE

...it will print:

0: This is line one
1: This is line two; the next is empty
2:
3: This is line four
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. I didn't know I could use parens to pipe multiple lines. Thanks.
0

You can do a simple:

$ java Test < file.txt

But if you absolutely need the pause command, you will have to do it on a script, or code pause behavior in Test class.

1 Comment

You can just do java Test < file.txt & pause

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.