go to previous page   go to home page   go to next page highlighting

Answer:

Mostly from the keyboard.


Input Redirection

A program that reads input from the keyboard can also read input from a text file. This is called input redirection, and is a feature of the command line interface of some operating systems.

Say that you have a program named Echo.java that reads characters from the keyboard and echoes them to the monitor.

import java.util.Scanner;

class Echo
{
  public static void main ( String[] args )
  {
    Scanner scan = new Scanner( System.in );
    String line;

    System.out.println("Enter your input:");
    line = scan.nextLine();

    System.out.println( "You typed: " + line );
   }
}

Here is how the program usually works:

C:\temp> java Echo
Enter your input: 
User types this.
You typed: User types this.
C:\temp>

Without making any changes to the program, its input can come from a disk file. Say that there is a file input.txt in the same subdirectory as the program, and that it contains the text:

This is text from the file.

You can do this:

C:\temp> java Echo < input.txt
Enter your input:
You typed: This is text from the file.
C:\temp> 

"< input.txt" connects the file input.txt to the program which then reads it instead of the keyboard. As with input redirection, this is a feature of the command line interface, not a feature specific to Java.

The program's output is sent to the monitor, including the (now useless) prompt.

The file input.txt must exist before the program is run. Create it with a text editor.

Compatibility Note: Input redirection as shown here works for the older command line of Windows. It also works for the command line of current and older versions of Linux and Unix. But it does not work for Windows PowerShell. For PowerShell do this:

C:\temp> type input.txt | java Echo
Enter your input:
You typed: This is text from the file.
C:\temp> 

The character | on the first line is the "vertical bar" character on the keyboard.


QUESTION 2:

Is there a limit to the size of the input file?


go to previous page   go to home page   go to next page