java的输入输出代码实现
时间: 2024-05-17 11:10:07 浏览: 17
Java的输入输出主要使用java.io包中的类和接口实现。以下是Java输入输出的一些代码实现:
1. 读取文件内容
```
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
File file = new File("test.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 写入文件内容
```
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
File file = new File("test.txt");
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write("Hello, World!");
bw.newLine();
bw.write("This is a test.");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
3. 从控制台读取输入
```
import java.util.Scanner;
public class ReadConsole {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入您的姓名:");
String name = scanner.nextLine();
System.out.println("您好," + name + "!");
scanner.close();
}
}
```
以上是Java输入输出的一些基本代码实现,希望对您有所帮助。
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)