使用Java进行文件操作:读写、复制、删除

原创 青旅半醒 2024-09-16 12:45 144阅读 0赞

在Java中,我们可以使用java.io包中的类来处理文件操作。以下是几种常见操作的示例:

  1. 读写文件
    ```java
    import java.io.*;

// 写入文件
public void writeToFile(String content, String fileName) throws IOException {
File file = new File(fileName);
// 如果文件不存在,创建它
if (!file.exists()) {
file.createNewFile();
}
// 使用Writer写入内容到文件中
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(content);
writer.close();
}

// 读取文件
public String readFromFile(String fileName) throws IOException {
File file = new File(fileName);
if (!file.exists()) {
throw new FileNotFoundException(“File does not exist: “ + fileName);
}
// 使用BufferedReader读取内容到字符串中
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder contentBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
contentBuilder.append(line).append(“\n”);
}
reader.close();
return contentBuilder.toString();
}

  1. 2. **复制文件**:
  2. ```java
  3. import java.io.*;
  4. public void copyFile(String source, String destination) throws IOException {
  5. FileInputStream fis = new FileInputStream(source);
  6. FileOutputStream fos = new FileOutputStream(destination);
  7. byte[] buffer = new byte[1024]; // 指定缓冲区大小
  8. while (fis.read(buffer) != -1) { // 读取源文件
  9. fos.write(buffer); // 写入目标文件
  10. }
  11. fis.close();
  12. fos.close();
  13. }
  1. 删除文件
    ```java
    import java.io.*;

public void deleteFile(String fileName) throws IOException {
File file = new File(fileName);
if (file.exists()) { // 文件存在,删除它
file.delete(); // 使用delete()方法删除文件
} else { // 文件不存在,不做处理
System.out.println(“File not found: “ + fileName);
}
}
```

以上就是使用Java进行文件操作的一些基本示例。根据实际需求,你可能需要使用更复杂的API或者类。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,144人围观)

还没有评论,来说两句吧...

相关阅读