Java 输入代码230


在 Java 中,有多种输入代码的方法,具体取决于您需要从何处获取输入。

从控制台输入

要从控制台获取用户输入,您可以使用 Scanner 类。以下示例演示如何读取一个字符串输入:```java
import ;
public class ConsoleInput {
public static void main(String[] args) {
Scanner scanner = new Scanner();
// 读取一行文本输入
String input = ();
// 打印用户输入
("输入内容:" + input);
();
}
}
```

从文件中输入

要从文件中读取输入,您可以使用 File 和 Scanner 类。以下示例演示如何读取一个文本文件的内容:```java
import ;
import ;
import ;
public class FileInput {
public static void main(String[] args) {
try {
// 创建一个 File 对象来表示文本文件
File file = new File("");
// 使用 Scanner 来读取文件内容
Scanner scanner = new Scanner(file);
// 循环读取文件中的每一行
while (()) {
String line = ();
// 打印文件中的每一行
("输入行:" + line);
}
();
} catch (FileNotFoundException e) {
// 处理文件未找到的情况
("找不到文件 ");
}
}
}
```

从其他程序输入

要从其他程序获取输入,您可以使用 PipedInputStream 和 PipedOutputStream 类。以下示例演示如何在两个 Java 程序之间使用管道进行通信:发送方程序:
```java
import ;
import ;
public class Sender {
public static void main(String[] args) {
try {
// 创建管道输出流
PipedOutputStream output = new PipedOutputStream();
// 连接管道输出流到另一个程序的管道输入流
// 这里假设接收方程序的管道输入流称为 "in"
(new PipedInputStream("in"));
// 发送数据到另一个程序
("你好,接收方程序!".getBytes());
();
} catch (IOException e) {
// 处理 I/O 错误
}
}
}
```
接收方程序:
```java
import ;
import ;
public class Receiver {
public static void main(String[] args) {
try {
// 创建管道输入流
PipedInputStream input = new PipedInputStream();
// 连接管道输入流到另一个程序的管道输出流
// 这里假设发送方程序的管道输出流称为 "out"
(new PipedOutputStream("out"));
// 从另一个程序接收数据
byte[] buffer = new byte[1024];
int length = (buffer);
// 打印接收到的数据
String message = new String(buffer, 0, length);
("接收到的消息:" + message);
();
} catch (IOException e) {
// 处理 I/O 错误
}
}
}
```

2024-10-29


上一篇:如何判断 Java 中给定变量是否为数组

下一篇:Java 数组的遍历