java创建文件并写入txt
时间: 2025-06-29 19:15:24 浏览: 6
### 创建文件并写入文本内容
在 Java 中,可以使用 `java.nio.file` 包中的类来创建文件并向其写入文本内容。下面是一个完整的例子,展示了如何实现这一功能[^1]。
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileWriteExample {
public static void main(String[] args) {
Path pathToFile = Paths.get("example.txt");
// Create file if not exists
try {
if (!Files.exists(pathToFile)) {
Files.createFile(pathToFile);
System.out.println("File created.");
}
} catch (IOException e) {
System.err.println("Exception occurred: " + e.getMessage());
}
// Write string to file
String contentToWrite = "This is some text that will be written into the file.";
try {
Files.write(pathToFile, contentToWrite.getBytes(), StandardOpenOption.APPEND);
System.out.println("Text has been appended to the file.");
} catch (IOException e) {
System.err.println("Exception occurred: " + e.getMessage());
}
}
}
```
此代码片段首先尝试创建名为 `example.txt` 的新文件(如果该文件尚不存在)。接着,向这个文件追加一段字符串作为内容。这里使用的 `StandardOpenOption.APPEND` 参数确保即使文件已存在也不会被覆盖而是追加内容。
阅读全文
相关推荐

















