用java创建一个.text文件并按 | 按行写入文字
时间: 2024-05-12 15:21:06 浏览: 12
以下是使用Java创建一个text文件并按 | 按行写入文字的示例代码:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriteExample {
public static void main(String[] args) {
String fileName = "example.txt";
String[] lines = {"This is the first line.", "This is the second line.", "This is the third line."};
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
for (String line : lines) {
writer.write(line + " | ");
writer.newLine();
}
writer.close();
System.out.println("File successfully written!");
} catch (IOException e) {
System.out.println("An error occurred while writing the file.");
e.printStackTrace();
}
}
}
```
这个程序创建了一个名为 "example.txt" 的文件,并在每行末尾添加了一个 | 符号。每个字符串都通过循环写入文件中,然后使用 BufferedWriter 的 newLine() 方法分隔每行。最后,程序关闭了写入器,以确保所有内容都被正确地写入了文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)