java.nio.file不存在_Java NIO Files.createFile()以NoSuchFileException失败
时间: 2024-03-02 10:48:53 浏览: 90
这个问题可能是由于指定的文件路径不存在而导致的。你可以尝试在创建文件之前先创建文件所在的目录,或者检查文件路径是否正确。此外,还可以使用Files.createDirectories()方法来自动创建不存在的目录。
以下是一个示例代码,用于创建一个文件并写入一些内容:
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFileExample {
public static void main(String[] args) {
String fileName = "example.txt";
String content = "Hello, world!";
Path filePath = Paths.get(fileName);
try {
// 如果文件不存在,则创建文件
if (!Files.exists(filePath)) {
// 创建文件所在的目录
Files.createDirectories(filePath.getParent());
// 创建文件
Files.createFile(filePath);
}
// 写入文件内容
Files.write(filePath, content.getBytes());
System.out.println("文件创建成功,并写入了以下内容:\n" + content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
你可以根据自己的需要修改文件名、文件路径和文件内容。另外,你也可以使用其他方法来读取和写入文件,例如Files.newBufferedWriter()和Files.newBufferedReader()方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)