You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java技术问题:如何将文本文件内容重定向为程序的键盘输入

Redirecting a Text File as Keyboard Input to Your Java Program

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 of name.txt and 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 select name.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 select name.txt. Click "Run" to test.

内容的提问来源于stack exchange,提问作者lordkennedy99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:34:30