用Scanner对象获取用户输入的字符串,然后写入"D:\\t01.txt"中
时间: 2023-10-09 20:12:23 浏览: 42
好的,以下是Java代码实现:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class WriteToFileExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要写入文件的内容:");
String content = scanner.nextLine();
scanner.close();
try {
FileWriter writer = new FileWriter("D:\\t01.txt");
writer.write(content);
writer.close();
System.out.println("写入成功!");
} catch (IOException e) {
System.out.println("写入失败:" + e.getMessage());
}
}
}
```
这段代码会让用户输入要写入文件的内容,然后将其写入到指定的文件"D:\\t01.txt"中。请注意,如果文件已经存在,那么它的内容将被覆盖。如果文件不存在,那么会自动创建。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)