java文件操作
时间: 2024-02-17 09:01:04 浏览: 29
Java提供了丰富的文件操作类和方法,可以方便地读写文件、创建目录、删除文件等操作。以下是一些常用的文件操作:
1. 读取文件内容:
```
File file = new File("filename.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
```
2. 写入文件内容:
```
File file = new File("filename.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello, world!");
writer.newLine();
writer.write("This is a test.");
writer.close();
```
3. 创建目录:
```
File dir = new File("path/to/directory");
if (!dir.exists()) {
dir.mkdirs();
}
```
4. 删除文件或目录:
```
File file = new File("filename.txt");
if (file.exists()) {
file.delete();
}
File dir = new File("path/to/directory");
if (dir.exists()) {
for (File f : dir.listFiles()) {
f.delete();
}
dir.delete();
}
```
5. 复制文件:
```
File source = new File("source.txt");
File dest = new File("dest.txt");
Files.copy(source.toPath(), dest.toPath());
```
以上是一些基本的文件操作,还有其他更高级的操作可以根据需要进行学习和使用。
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)