溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java?Files和Paths怎么使用demo

發(fā)布時(shí)間:2023-03-31 11:21:41 來(lái)源:億速云 閱讀:97 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要講解了“Java Files和Paths怎么使用demo”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“Java Files和Paths怎么使用demo”吧!

前言

Java Files和Paths是Java 7中引入的新API,用于處理文件和目錄。Files類提供了許多有用的靜態(tài)方法來(lái)操作文件和目錄,而Path類則表示文件系統(tǒng)中的路徑。

創(chuàng)建文件和目錄

在Java中創(chuàng)建文件和目錄非常簡(jiǎn)單。我們可以使用Files類的createFile()方法和createDirectory()方法來(lái)創(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");
		//多級(jí)目錄
		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)建多級(jí)目錄
         try {
             Files.createDirectories(pathDirectories);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

上面的代碼會(huì)創(chuàng)建一個(gè)名為“example.txt”的文件和一個(gè)名為“exampleDir”的目錄。如果文件或目錄已經(jīng)存在,這些方法將拋出異常。
createDirectories方法會(huì)創(chuàng)建多級(jí)目錄,上級(jí)目錄不存在的話,直接創(chuàng)建。

寫入文件

Java提供了多種方式來(lái)寫入文件。我們可以使用Files類的write()方法來(lái)將數(shù)據(jù)寫入文件。

示例:

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é)數(shù)組
        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);
        } 
    }
}

上面的代碼將數(shù)據(jù)寫入“example.txt”文件。我們可以使用write()方法將字節(jié)數(shù)組、字符串或字符串列表寫入文件。

讀取文件

Java提供了多種方式來(lái)讀取文件。我們可以使用Files類的readAllBytes()方法、readAllLines()方法或newBufferedReader()方法來(lái)讀取文件。

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é)數(shù)組
        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()方法。

// 刪除一個(gè)文件
Path fileToDeletePath = Paths.get("fileToDelete.txt");
try {
    Files.delete(fileToDeletePath);
    System.out.println("文件刪除成功");
} catch (IOException e) {
    System.out.println("文件刪除失敗");
}

// 刪除一個(gè)目錄
Path dirToDeletePath = Paths.get("dirToDelete");
try {
    Files.delete(dirToDeletePath);
    System.out.println("目錄刪除成功");
} catch (IOException e) {
    System.out.println("目錄刪除失敗");
}


//如果文件存在才刪除,不會(huì)拋出異常
 try {
 		//返回布爾值
       Files.deleteIfExists("dirToDelete/dir");
   } catch (IOException e) {
       throw new RuntimeException(e);
   }

復(fù)制文件

// 復(fù)制一個(gè)文件
//資源地址
Path sourceFilePath = Paths.get("sourceFile.txt");
//目標(biāo)地址
Path targetFilePath = Paths.get("targetFile.txt");


try {
    Files.copy(sourceFilePath, targetFilePath,StandardCopyOption.REPLACE_EXISTING);
    System.out.println("文件復(fù)制成功");
} catch (IOException e) {
    System.out.println("文件復(fù)制失?。?quot; + e.getMessage());
}

復(fù)制目錄

// 復(fù)制一個(gè)目錄
Path sourceDirPath = Paths.get("C:/Users/username/Desktop/sourceDir");
Path targetDirPath = Paths.get("C:/Users/username/Desktop/targetDir");
try {
//CopyFileVisitor是需要自己實(shí)現(xiàn)的

    Files.walkFileTree(sourceDirPath, new CopyFileVisitor(sourceDirPath, targetDirPath));
    System.out.println("目錄復(fù)制成功");
} catch (IOException e) {
    System.out.println("目錄復(fù)制失?。?quot; + 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;
    }

    @Override
    public 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;
    }

    @Override
    public 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()方法中,我們將源目錄下的子目錄逐個(gè)創(chuàng)建到目標(biāo)目錄中。在創(chuàng)建過(guò)程中,我們使用Files.copy()方法將目錄復(fù)制到目標(biāo)目錄中。由于目標(biāo)目錄可能已經(jīng)存在,因此我們?cè)贔iles.copy()方法中使用了FileAlreadyExistsException異常進(jìn)行處理。

在visitFile()方法中,我們將源目錄下的文件逐個(gè)復(fù)制到目標(biāo)目錄中。在復(fù)制過(guò)程中,我們使用Files.copy()方法將文件復(fù)制到目標(biāo)目錄中,并使用StandardCopyOption.REPLACE_EXISTING選項(xiàng)替換現(xiàn)有文件。

移動(dòng)或重命名

    try {
    //這個(gè)操作可以做移動(dòng)或重命名
       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);
        }

該方法接受三個(gè)參數(shù):

  • start:表示要遍歷的根目錄的路徑。

  • maxDepth:表示要遍歷的最大深度。如果maxDepth為0,則只遍歷根目錄,不遍歷其子目錄。如果maxDepth為正整數(shù),則遍歷根目錄和所有深度不超過(guò)maxDepth的子目錄。如果maxDepth為負(fù)數(shù),則遍歷根目錄和所有子目錄。

  • options:表示遍歷選項(xiàng)??蛇x項(xiàng)包括FileVisitOption.FOLLOW_LINKS和FileVisitOption.NOFOLLOW_LINKS。

  • 如果選擇FOLLOW_LINKS選項(xiàng),則遍歷符號(hào)鏈接指向的目錄;

  • 如果選擇NOFOLLOW_LINKS選項(xiàng),則遍歷符號(hào)鏈接本身

獲取文件屬性

 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("判斷是否是一個(gè)文件: " + 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("文件存儲(chǔ)在SSD還是HDD: " + Files.getFileStore(path));
            System.out.println("文件修改時(shí)間:" + Files.getLastModifiedTime(path));
            System.out.println("文件擁有者: " + Files.getOwner(path));
            System.out.println("文件類型: " + Files.probeContentType(path));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

感謝各位的閱讀,以上就是“Java Files和Paths怎么使用demo”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)Java Files和Paths怎么使用demo這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI