Java中,File類是處理文件和目錄的主要類之一,它提供了一些實用的方法來操作文件和目錄,例如創建、刪除、重命名、迭代目錄等。在本文中,我們將從多個方面深入了解File類,讓你更好的使用它。
一、創建和刪除文件
1、創建一個新文件
File file = new File("path/to/your/file.txt"); boolean success = file.createNewFile(); if (success) { System.out.println("File created successfully!"); }
2、刪除一個文件
File file = new File("path/to/your/file.txt"); boolean success = file.delete(); if (success) { System.out.println("File deleted successfully!"); }
二、讀取和寫入文件
1、讀取文件內容
File file = new File("path/to/your/file.txt"); try (Scanner scanner = new Scanner(file)) { while(scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); } } catch (IOException e) { e.printStackTrace(); }
2、寫入文件內容
File file = new File("path/to/your/file.txt"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { writer.write("Hello, World!"); } catch (IOException e) { e.printStackTrace(); }
三、目錄操作
1、遍歷目錄
File dir = new File("path/to/your/directory"); File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { System.out.println("Directory: " + file.getAbsolutePath()); } else { System.out.println("File: " + file.getAbsolutePath()); } }
2、創建目錄和刪除目錄
File dir = new File("path/to/your/directory"); boolean success = dir.mkdir(); // 創建目錄 // 或者使用 dir.mkdirs() 創建多級目錄 if (success) { System.out.println("Directory created successfully!"); } boolean success = dir.delete(); // 刪除目錄 if (success) { System.out.println("Directory deleted successfully!"); }
四、其他操作
1、判斷文件是否存在
File file = new File("path/to/your/file.txt"); boolean exists = file.exists(); if (exists) { System.out.println("File exists!"); }
2、獲取文件的大小和最後修改時間
File file = new File("path/to/your/file.txt"); long size = file.length(); System.out.println("File size: " + size + " bytes"); long lastModified = file.lastModified(); System.out.println("Last modified: " + new Date(lastModified));
3、重命名文件
File file = new File("path/to/your/file.txt"); boolean success = file.renameTo(new File("path/to/your/newfile.txt")); if (success) { System.out.println("File renamed successfully!"); }
以上是File類的常見操作,我們可以根據具體需求結合實際場景進行使用。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/195614.html