在Java中进行文件操作:读写、复制、删除等实例

原创 向右看齐 2024-10-08 07:36 123阅读 0赞

在Java中,我们可以使用java.io包下的类来进行文件的操作。下面是一些常见的操作示例:

  1. 读写文件
    ```java
    import java.io.File;
    import java.io.IOException;

// 写入文件
try (FileWriter writer = new FileWriter(“example.txt”)) {
writer.write(“Hello, World!”);
}

// 读取文件
try (FileReader reader = new FileReader(“example.txt”)) {
String content = new String(reader.read());
System.out.println(content); // 输出 “Hello, World!”
}

  1. 2. **复制文件**:
  2. ```java
  3. import java.io.File;
  4. import java.io.IOException;
  5. public class FileCopyExample {
  6. public static void main(String[] args) {
  7. // 源文件
  8. File sourceFile = new File("source.txt");
  9. // 目标文件
  10. File destinationFile = new File("destination.txt");
  11. // 复制文件
  12. try {
  13. copyFile(sourceFile, destinationFile);
  14. System.out.println("File copied successfully.");
  15. } catch (IOException e) {
  16. System.err.println("Error occurred while copying file: " + e.getMessage());
  17. }
  18. }
  19. private static void copyFile(File sourceFile, File destinationFile) throws IOException {
  20. // 检查源文件是否存在
  21. if (!sourceFile.exists()) {
  22. throw new FileNotFoundException("Source file does not exist.");
  23. }
  24. // 检查目标文件是否存在并可写
  25. if (destinationFile.exists() && !destinationFile.canWrite())) {
  26. throw new IllegalAccessException("Destination file exists and cannot be written by the current user.");
  27. }
  28. // 复制文件
  29. FileInputStream fis = new FileInputStream(sourceFile);
  30. FileOutputStream fos = new FileOutputStream(destinationFile);
  31. byte[] buffer = new byte[1024]; // 读写缓冲区大小
  32. while (true) {
  33. int readSize = fis.read(buffer); // 读取数据
  34. if (readSize == -1) { // 如果读取完毕
  35. break;
  36. } else if (readSize == 0) { // 如果读取到空数据
  37. fos.write(buffer, 0)); // 写回缓冲区起始位置的数据
  38. continue; // 继续循环,下一次再尝试读取
  39. }
  40. fos.write(buffer, 0), readSize); // 写入目标文件
  41. }
  42. fis.close(); // 关闭输入流
  43. fos.close(); // 关闭输出流
  44. }
  45. }
  1. 删除文件
    ```java
    import java.io.File;

public class FileDeleteExample {
public static void main(String[] args) {
// 文件对象
File file = new File(“example.txt”);

  1. // 删除文件
  2. if (file.delete()) {
  3. System.out.println("File deleted successfully.");
  4. } else {
  5. System.err.println("Failed to delete the file. Reason: " + file.delete()));
  6. }
  7. }

}
```

以上就是Java中进行文件操作的一些实例。

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

发表评论

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

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

相关阅读