分銷平臺網站建設桂林武漢搜索排名提升
前言
Java Files和Paths是Java 7中引入的新API,用于處理文件和目錄。Files類提供了許多有用的靜態(tài)方法來操作文件和目錄,而Path類則表示文件系統(tǒng)中的路徑。
創(chuàng)建文件和目錄
在Java中創(chuàng)建文件和目錄非常簡單。我們可以使用Files類的createFile()方法和createDirectory()方法來創(chuàng)建文件和目錄
示例:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;public class CreateFileAndDirectory {public static void main(String[] args) throws IOException {//文件Path pathToFile = Paths.get("example.txt");//目錄Path pathToDir = Paths.get("exampleDir");//多級目錄Path pathDirectories = Paths.get("java\exampleDir\pathDirectories\dir");// 創(chuàng)建文件try {Files.createFile(pathToFile);} catch (IOException e) {throw new RuntimeException(e);}// 創(chuàng)建目錄try {Files.createDirectory(pathToDir);} catch (IOException e) {throw new RuntimeException(e);}//創(chuàng)建多級目錄try {Files.createDirectories(pathDirectories);} catch (IOException e) {throw new RuntimeException(e);}}
}
上面的代碼會創(chuàng)建一個名為“example.txt”的文件和一個名為“exampleDir”的目錄。如果文件或目錄已經存在,這些方法將拋出異常。
createDirectories方法會創(chuàng)建多級目錄,上級目錄不存在的話,直接創(chuàng)建。
寫入文件
Java提供了多種方式來寫入文件。我們可以使用Files類的write()方法來將數據寫入文件。
示例:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.Arrays;public class WriteToFile {public static void main(String[] args) throws IOException {Path path = Paths.get("example.txt");// 寫入字節(jié)數組byte[] bytes = "Hello, world!".getBytes();try {Files.write(path, bytes);} catch (IOException e) {throw new RuntimeException(e);}// 寫入字符串String text = "Hello, world!";try {Files.write(path, text.getBytes());} catch (IOException e) {throw new RuntimeException(e);}// 寫入字符串列表Iterable<String> lines = Arrays.asList("line 1", "line 2", "line 3");try {Files.write(path, lines);} catch (IOException e) {throw new RuntimeException(e);} }
}
上面的代碼將數據寫入“example.txt”文件。我們可以使用write()方法將字節(jié)數組、字符串或字符串列表寫入文件。
讀取文件
Java提供了多種方式來讀取文件。我們可以使用Files類的readAllBytes()方法、readAllLines()方法或newBufferedReader()方法來讀取文件。
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;public class ReadFromFile {public static void main(String[] args) throws IOException {Path path = Paths.get("example.txt");// 讀取字節(jié)數組byte[] bytes = Files.readAllBytes(path);System.out.println(new String(bytes));// 讀取字符串列表List<String> lines = Files.readAllLines(path);// 使用BufferedReader讀取文件BufferedReader reader = Files.newBufferedReader(path);String line = null;while ((line = reader.readLine()) != null
刪除文件或目錄
刪除文件或目錄可以使用Files類的delete()方法。
// 刪除一個文件
Path fileToDeletePath = Paths.get("fileToDelete.txt");
try {Files.delete(fileToDeletePath);System.out.println("文件刪除成功");
} catch (IOException e) {System.out.println("文件刪除失敗");
}// 刪除一個目錄
Path dirToDeletePath = Paths.get("dirToDelete");
try {Files.delete(dirToDeletePath);System.out.println("目錄刪除成功");
} catch (IOException e) {System.out.println("目錄刪除失敗");
}//如果文件存在才刪除,不會拋出異常try {//返回布爾值Files.deleteIfExists("dirToDelete/dir");} catch (IOException e) {throw new RuntimeException(e);}
復制文件
// 復制一個文件
//資源地址
Path sourceFilePath = Paths.get("sourceFile.txt");
//目標地址
Path targetFilePath = Paths.get("targetFile.txt");try {Files.copy(sourceFilePath, targetFilePath,StandardCopyOption.REPLACE_EXISTING);System.out.println("文件復制成功");
} catch (IOException e) {System.out.println("文件復制失敗:" + e.getMessage());
}
復制目錄
// 復制一個目錄
Path sourceDirPath = Paths.get("C:/Users/username/Desktop/sourceDir");
Path targetDirPath = Paths.get("C:/Users/username/Desktop/targetDir");
try {
//CopyFileVisitor是需要自己實現的Files.walkFileTree(sourceDirPath, new CopyFileVisitor(sourceDirPath, targetDirPath));System.out.println("目錄復制成功");
} catch (IOException e) {System.out.println("目錄復制失敗:" + e.getMessage());
}
CopyFileVisitor
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;public class CopyFileVisitor extends SimpleFileVisitor<Path> {private final Path sourceDir;private final Path targetDir;public CopyFileVisitor(Path sourceDir, Path targetDir) {this.sourceDir = sourceDir;this.targetDir = targetDir;}@Overridepublic FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {Path targetPath = targetDir.resolve(sourceDir.relativize(dir));try {Files.copy(dir, targetPath);} catch (FileAlreadyExistsException e) {if (!Files.isDirectory(targetPath)) {throw e;}}return FileVisitResult.CONTINUE;}@Overridepublic FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {Path targetPath = targetDir.resolve(sourceDir.relativize(file));Files.copy(file, targetPath, StandardCopyOption.REPLACE_EXISTING);return FileVisitResult.CONTINUE;}
}
在preVisitDirectory()方法中,我們將源目錄下的子目錄逐個創(chuàng)建到目標目錄中。在創(chuàng)建過程中,我們使用Files.copy()方法將目錄復制到目標目錄中。由于目標目錄可能已經存在,因此我們在Files.copy()方法中使用了FileAlreadyExistsException異常進行處理。
在visitFile()方法中,我們將源目錄下的文件逐個復制到目標目錄中。在復制過程中,我們使用Files.copy()方法將文件復制到目標目錄中,并使用StandardCopyOption.REPLACE_EXISTING選項替換現有文件。
移動或重命名
try {//這個操作可以做移動或重命名Files.move(Paths.get("source.txt"),Paths.get("target.txt"), StandardCopyOption.REPLACE_EXISTING);} catch (IOException e) {throw new RuntimeException(e);}
遍歷目錄
Path start = Paths.get("sourceDir");int maxDepth = Integer.MAX_VALUE;try {Files.walk(start, maxDepth).forEach(System.out::println);} catch (IOException e) {throw new RuntimeException(e);}
該方法接受三個參數:
- start:表示要遍歷的根目錄的路徑。
- maxDepth:表示要遍歷的最大深度。如果maxDepth為0,則只遍歷根目錄,不遍歷其子目錄。如果maxDepth為正整數,則遍歷根目錄和所有深度不超過maxDepth的子目錄。如果maxDepth為負數,則遍歷根目錄和所有子目錄。
- options:表示遍歷選項。可選項包括FileVisitOption.FOLLOW_LINKS和FileVisitOption.NOFOLLOW_LINKS。
如果選擇FOLLOW_LINKS選項,則遍歷符號鏈接指向的目錄;
如果選擇NOFOLLOW_LINKS選項,則遍歷符號鏈接本身
獲取文件屬性
try {Path path = Paths.get("F:\\java\\2.txt").toAbsolutePath();System.out.println("文件是否存在: " + Files.exists(path));System.out.println("是否是目錄: " + Files.isDirectory(path));System.out.println("是否是可執(zhí)行文件: " + Files.isExecutable(path));System.out.println("是否可讀: " + Files.isReadable(path));System.out.println("判斷是否是一個文件: " + Files.isRegularFile(path));System.out.println("是否可寫: " + Files.isWritable(path));System.out.println("文件是否不存在: " + Files.notExists(path));System.out.println("文件是否隱藏: " + Files.isHidden(path));System.out.println("文件大小: " + Files.size(path));System.out.println("文件存儲在SSD還是HDD: " + Files.getFileStore(path));System.out.println("文件修改時間:" + Files.getLastModifiedTime(path));System.out.println("文件擁有者: " + Files.getOwner(path));System.out.println("文件類型: " + Files.probeContentType(path));} catch (IOException e) {throw new RuntimeException(e);}