Java技术问题:如何将文本文件内容重定向为程序的键盘输入
Got it, let's break this down clearly—you don't need to tweak your Java code at all, this is all handled right from your command line (or IDE, if you prefer). Here's exactly how to do it, plus an explanation of what's going on under the hood.
Basic Command Line Method (No Code Changes Needed)
This is the standard approach across all major operating systems. It leverages your OS's input redirection feature to feed the file content into your program as if it was typed manually.
1. First, compile your Java program (if you haven't already)
If your main class is named, say, UserInputProgram.java, run this in your terminal/command prompt to generate the .class file:
javac UserInputProgram.java
2. Run the program with file redirection
Use the < operator to tell your OS to replace the default keyboard input with the contents of name.txt:
For Linux/macOS (Terminal)
java UserInputProgram < name.txt
For Windows (Command Prompt/PowerShell)
The syntax is identical—Windows uses the same redirection operator:
java UserInputProgram < name.txt
What Does the < Operator Actually Do?
Let me demystify this so you understand why it works:
- By default, your Java program reads input from standard input (
System.in), which is connected to your keyboard. - The
<operator is a shell command that redirects this standard input source. Instead of pulling input from your keyboard, it tells the OS to read the contents ofname.txtand pass it to your program line by line (or as a stream, depending on how your program reads input). - Your Java program has no idea the difference—it just reads input like it always would, but gets it from the file instead of your keystrokes.
Bonus: Setting Up Redirection in an IDE
If you prefer running your program from an IDE like IntelliJ or Eclipse instead of the command line, you can configure input redirection there too:
- IntelliJ IDEA: Go to
Run > Edit Configurations, select your program's run configuration. Look for the "Redirect input from" field, click the folder icon, and selectname.txt. Then run the program as usual. - Eclipse: Right-click your program >
Run As > Run Configurations. Go to the "Arguments" tab, scroll to the "Standard Input and Output" section, check the "File" radio button, and browse to selectname.txt. Click "Run" to test.
内容的提问来源于stack exchange,提问作者lordkennedy99

