使用Java实现文件操作:读写、复制和删除

原创 喜欢ヅ旅行 2024-09-24 14:45 126阅读 0赞

在Java中,我们可以使用java.io.File类进行文件操作。以下是一些基本的文件操作方法:

  1. 创建文件

    1. File file = new File("path_to_file"); // path can be relative or absolute
    2. if (file.exists()) { // check if the file already exists
    3. System.out.println("File already exists.");
    4. } else {
    5. file.createNewFile(); // create a new file, if it doesn't exist yet
    6. System.out.println("File created successfully.");
    7. }
  2. 读写文件
    ```java
    // Write to file
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(file)))) {
    writer.write(“Hello, World!”);
    writer.newLine(); // write a newline character
    writer.flush(); // flush the buffer to ensure the data is written immediately
    }
    catch (IOException e) {
    System.out.println(“Error occurred while writing to file: “ + e.getMessage());
    }

// Read from file
try (BufferedReader reader = new BufferedReader(new FileReader(file)))) {
String line;
while ((line = reader.readLine()) != null) { // read until the end of file or a null value
System.out.println(line);
}
}
catch (IOException e) {
System.out.println(“Error occurred while reading from file: “ + e.getMessage());
}

  1. 3. **复制文件**:
  2. ```java
  3. // Copy file to another location using absolute path
  4. try (FileInputStream fis = new FileInputStream(file));
  5. FileOutputStream fos = new FileOutputStream("path_to_destination_file")) as FileInputStream, FileOutputStream {
  6. byte[] buffer = new byte[1024]; // define buffer size
  7. int bytesRead = fis.read(buffer); // read from source file
  8. if (bytesRead != -1) { // if data is read successfully
  9. fos.write(buffer, 0, bytesRead); // write to destination file
  10. System.out.println("File copied successfully.");
  11. } else {
  12. System.out.println("Error occurred while copying file: " + fis.readError()));
  13. }
  14. }
  15. catch (IOException e) {
  16. System.out.println("Error occurred while copying file: " + e.getMessage());
  17. }
  1. 删除文件
    1. // Delete file using absolute path
    2. try {
    3. File fileToDelete = new File("path_to_file"); // replace with your file's path
    4. if (fileToDelete.exists()) { // check if the file exists
    5. fileToDelete.delete(); // delete the file
    6. System.out.println("File deleted successfully.");
    7. } else {
    8. System.out.println("Error occurred while deleting file: File doesn't exist.");
    9. }
    10. } catch (IOException e) {
    11. System.out.println("Error occurred while deleting file: " + e.getMessage());
    12. }

请确保提供正确的文件路径,否则可能会抛出FileNotFoundException

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

发表评论

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

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

相关阅读