最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java文件基本操作總結(jié)

 更新時(shí)間:2021年06月21日 09:05:15   作者:少年啊!  
今天給大家?guī)?lái)的是關(guān)于Java基礎(chǔ)的相關(guān)知識(shí),文章圍繞著Java文件操作展開(kāi),文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下

File文件類

  • java.io.File是文件和目錄的重要類(JDK6及以前是唯一)
  • 目錄也使用File類進(jìn)行表示
  • File類與操作系統(tǒng)無(wú)關(guān),但會(huì)受到操作系統(tǒng)的權(quán)限限制
  • 常用方法createNewFile , delete , exists , getAbsolutePath , getName , getParent , getPathisDirectory , isFile , length , listFiles , mkdir , mkdirs
  • File不涉及到具體的文件內(nèi)容、只會(huì)涉及屬性
public static void main(String[] args) {
    // 創(chuàng)建目錄
    File directory = new File("D:/temp");
    boolean directoryDoesNotExists = ! directory.exists();
    if (directoryDoesNotExists) {
        // mkdir是創(chuàng)建單級(jí)目錄
        // mkdirs是連續(xù)創(chuàng)建多級(jí)目錄
        directory.mkdirs();

    }
    // 創(chuàng)建文件
    File file = new File("D:/temp/test.txt");
    boolean fileDoesNotExsits = ! file.exists();
    if (fileDoesNotExsits) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 遍歷directory下的所有文件消息
    File[] files = directory.listFiles();
    for (File file1 : files) {
        System.out.println(file1.getPath());
    }

}

運(yùn)行結(jié)果:

D:\temp\test.txt

Java NIO

  • Java 7提出的NIO包,提出新的文件系統(tǒng)類
  • Path , Files , DirectoryStream , FileVisitor , FileSystem
  • 是對(duì)java.io.File的有益補(bǔ)充
  • 文件復(fù)制和移動(dòng)
  • 文件相對(duì)路徑
  • 遞歸遍歷目錄
  • 遞歸刪除目錄

Path類

public static void main(String[] args) {
    // Path和java.io.File基本類似
    Path path = FileSystems.getDefault().getPath("D:/temp", "abc.txt");
    // D:/ 返回1 D:/temp 返回2
    System.out.println(path.getNameCount());

    // 用File的toPath()方法獲取Path對(duì)象
    File file = new File("D:/temp/abc.txt");
    Path path1 = file.toPath();
    System.out.println(path.compareTo(path1)); // 結(jié)果為0 說(shuō)明兩個(gè)path相等
    // 獲取Path方法三
    Path path3 = Paths.get("D:/temp", "abc.txt");
    // 判斷文件是否可讀
    System.out.println("文件是否可以讀取: " + Files.isReadable(path));
}

Files類

public static void main(String[] args) {
    // 移動(dòng)文件
    moveFile();
    // 訪問(wèn)文件屬性
    fileAttributes();
    // 創(chuàng)建目錄
    createDirectory();
}

private static void createDirectory() {
    Path path = Paths.get("D:/temp/test");
    try {
        // 創(chuàng)建文件夾
        if (Files.notExists(path)) {
            Files.createDirectory(path);
        } else {
            System.out.println("文件夾創(chuàng)建失敗");
        }
        Path path2 = path.resolve("a.java");
        Path path3 = path.resolve("b.java");
        Path path4 = path.resolve("c.txt");
        Path path5 = path.resolve("d.jpg");
        Files.createFile(path2);
        Files.createFile(path3);
        Files.createFile(path4);
        Files.createFile(path5);

        // 不帶條件的遍歷輸出
        DirectoryStream<Path> listDirectory = Files.newDirectoryStream(path);
        for (Path path1 : listDirectory) {
            System.out.println(path1.getFileName());
        }
        // 創(chuàng)建一個(gè)帶有過(guò)濾器,過(guò)濾文件名以java txt結(jié)尾的文件
        DirectoryStream<Path> pathsFilter = Files.newDirectoryStream(path, "*.{java,txt}");
        for (Path item : pathsFilter) {
            System.out.println(item.getFileName());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@SuppressWarnings("all")
private static void fileAttributes() {
    Path path = Paths.get("D:/temp");
    // 判斷是否是目錄
    System.out.println(Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS));
    try {
        // 獲取文件的基礎(chǔ)屬性
        BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
        // 判斷是否是目錄
        System.out.println(attributes.isDirectory());
        // 獲取文件最后修改時(shí)間
        System.out.println(new Date(attributes.lastModifiedTime().toMillis()).toLocaleString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static void moveFile() {
    Path from = Paths.get("D:/temp", "text.txt");
    // 將文件移動(dòng)到D:/temp/test/text.txt, 如果目標(biāo)文件以存在則替換
    Path to = from.getParent().resolve("test/text.txt");
    try {
        // 文件大小bytes
        System.out.println(Files.size(from));
        // 調(diào)用文件移動(dòng)方法,如果目標(biāo)文件已存在則替換
        Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

遞歸遍歷查找指定文件

public class Demo2 {
    public static void main(String[] args) {
        // 查找以.jpg結(jié)尾的
        String ext = "*.jpg";
        Path fileTree = Paths.get("D:/temp/");
        Search search = new Search(ext);
        EnumSet<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
        try {
            Files.walkFileTree(fileTree, options, Integer.MAX_VALUE, search);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class Search implements FileVisitor {
    private PathMatcher matcher;
    public Search(String ext) {
        this.matcher = FileSystems.getDefault().getPathMatcher("glob:" + ext);
    }

    public void judgeFile(Path file) throws IOException {
        Path name = file.getFileName();
        if (name != null && matcher.matches(name)) {
            // 文件名匹配
            System.out.println("匹配的文件名: " + name);
        }
    }
    // 訪問(wèn)目錄前調(diào)用
    @Override
    public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) throws IOException {
        return FileVisitResult.CONTINUE;
    }
    // 訪問(wèn)文件時(shí)調(diào)用
    @Override
    public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
        judgeFile((Path) file);
        return FileVisitResult.CONTINUE;
    }
    // 訪問(wèn)文件失敗后調(diào)用
    @Override
    public FileVisitResult visitFileFailed(Object file, IOException exc) throws IOException {
        return FileVisitResult.CONTINUE;
    }
    // 訪問(wèn)一個(gè)目錄后調(diào)用
    @Override
    public FileVisitResult postVisitDirectory(Object dir, IOException exc) throws IOException {
        System.out.println("postVisit: " + (Path) dir);
        return FileVisitResult.CONTINUE;
    }
}

運(yùn)行結(jié)果:

匹配的文件名: d.jpg
postVisit: D:\temp\test
postVisit: D:\temp

Java的IO包

  • Java讀寫(xiě)文件,只能以數(shù)據(jù)流的形式進(jìn)行讀寫(xiě)
  • java.io包中
  • 節(jié)點(diǎn)類:直接對(duì)文件進(jìn)行讀寫(xiě)
  • 包裝類:
  • 1、轉(zhuǎn)換類:字節(jié) / 字符 / 數(shù)據(jù)類型的轉(zhuǎn)化類 。
  • 2、裝飾類:裝飾節(jié)點(diǎn)類。

節(jié)點(diǎn)類

  • 直接操作文件類
  • InputStream,OutStream(字節(jié))
  • FileInputStream , FileOutputStream
  • Reader , Writer(字符)
  • FileReader , FileWriter

轉(zhuǎn)換類

  • 從字符到字節(jié)之間的轉(zhuǎn)化
  • InputStreamReader: 文件讀取時(shí)字節(jié),轉(zhuǎn)化為Java能理解的字符
  • OutputStreamWriter: Java將字符轉(zhuǎn)化為字節(jié)輸入到文件中

裝飾類

  • DataInputStream , DataOutputStream :封裝數(shù)據(jù)流
  • BufferedInputStream ,BufferOutputStream:緩存字節(jié)流
  • BufferedReader , BufferedWriter:緩存字符流

文本文件的讀寫(xiě)

寫(xiě)操作

public static void main(String[] args) {
    writeFile();
}

public static void writeFile(){
    try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:/temp/demo3.txt")))) {
        bw.write("hello world");
        bw.newLine();
        bw.write("Java Home");
        bw.newLine();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Demo3.txt文件內(nèi)容

hello world
Java Home

讀操作

public static void main(String[] args) {
    readerFile();
}

private static void readerFile() {
    String line = "";
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:/temp/demo3.txt")))) {
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

運(yùn)行結(jié)果:

hello world
Java Home

二進(jìn)制文件讀寫(xiě)java

public static void main(String[] args) {
    writeFile();
}

private static void writeFile() {
    try (DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("D:/temp/test.dat")))) {
        dos.writeUTF("hello");
        dos.writeUTF("hello world is test bytes");
        dos.writeInt(20);
        dos.writeUTF("world");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

文件內(nèi)容

hellohello world is test bytes world

讀操作

public static void main(String[] args) {
   readFile();
}

private static void readFile() {
    try (DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("D:/temp/test.dat")))) {
        System.out.println(in.readUTF() + in.readUTF() + in.readInt() + in.readUTF());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

運(yùn)行結(jié)果:

hellohello world is test bytes20world

ZIP文件的讀寫(xiě)

  • zip文件操作類:java.util.zip包中
  • java.io.InputStream , java.io.OutputStream的子類
  • ZipInputStream , ZipOutputStream壓縮文件輸入 / 輸出流
  • ZipEntry壓縮項(xiàng)

多個(gè)文件壓縮

// 多個(gè)文件壓縮
public static void main(String[] args) {
    zipFile();
}
public static void zipFile() {
    File file = new File("D:/temp");
    File zipFile = new File("D:/temp.zip");
    FileInputStream input = null;
    try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
        // 添加注釋
        zos.setComment(new String("多個(gè)個(gè)文件壓縮".getBytes(),"UTF-8"));

        // 壓縮過(guò)程
        int temp = 0;
        // 判斷是否為文件夾
        if (file.isDirectory()) {
            File[] listFile = file.listFiles();
            for (int i = 0; i < listFile.length; i++) {
                    // 定義文件的輸出流
                    input = new FileInputStream(listFile[i]);
                    // 設(shè)置Entry對(duì)象
                    zos.putNextEntry(new ZipEntry(file.getName() +
                            File.separator + listFile[i].getName() ));
                    System.out.println("正在壓縮: " + listFile[i].getName());
                    // 讀取內(nèi)容
                    while ((temp = input.read()) != -1) {
                        // 壓縮輸出
                        zos.write(temp);
                    }
                    // 關(guān)閉輸入流
                    input.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

注意:壓縮的文件夾不能有子目錄,否則會(huì)報(bào)FileNotFoundException: D:\temp\test (拒絕訪問(wèn)。),這是由于input = new FileInputStream(listFile[i]);讀取的文件類型是文件夾導(dǎo)致的

多個(gè)文件解壓縮

// 多個(gè)文件解壓縮
public static void main(String[] args) throws Exception{
    // 待解壓的zip文件,需要在zip文件上構(gòu)建輸入流,讀取數(shù)據(jù)到Java中
    File file = new File("C:\\Users\\Wong\\Desktop\\test.zip");

    // 輸出文件的時(shí)候要有文件夾的操作
    File outFile = null;
    // 實(shí)例化ZipEntry對(duì)象
    ZipFile zipFile = new ZipFile(file);

    // 定義解壓的文件名
    OutputStream out = null;
    // 定義輸入流,讀取每個(gè)Entry
    InputStream input = null;
    // 每一個(gè)壓縮Entry
    ZipEntry entry = null;
    
    // 定義壓縮輸入流,實(shí)例化ZipInputStream
    try (ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file))) {
        // 遍歷壓縮包中的文件
        while ((entry = zipInput.getNextEntry()) != null) {
            System.out.println("解壓縮 " + entry.getName().replaceAll("/", "") + " 文件");
            // 定義輸出的文件路徑
            outFile = new File("D:/" + entry.getName());
            
            boolean outputDirectoryNotExsits = !outFile.getParentFile().exists();
            // 當(dāng)輸出文件夾不存在時(shí)
            if (outputDirectoryNotExsits) {
                // 創(chuàng)建輸出文件夾
                outFile.getParentFile().mkdirs();
            }
            
            boolean outFileNotExists = !outFile.exists();
            // 當(dāng)輸出文件不存在時(shí)
            if (outFileNotExists) {
                if (entry.isDirectory()) {
                    outFile.mkdirs();
                } else {
                    outFile.createNewFile();
                }
            }

            boolean entryNotDirctory = !entry.isDirectory();
            if (entryNotDirctory) {
                input = zipFile.getInputStream(entry);
                out = new FileOutputStream(outFile);
                int temp = 0;
                while ((temp = input.read()) != -1) {
                    out.write(temp);
                }
                input.close();
                out.close();
                System.out.println("解壓縮成功");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

到此這篇關(guān)于Java文件基本操作總結(jié)的文章就介紹到這了,更多相關(guān)Java文件基本操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java多線程批量數(shù)據(jù)導(dǎo)入的方法詳解

    Java多線程批量數(shù)據(jù)導(dǎo)入的方法詳解

    這篇文章主要介紹了Java多線程批量數(shù)據(jù)導(dǎo)入的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,下面小編和大家來(lái)一起學(xué)習(xí)下吧
    2019-06-06
  • maven項(xiàng)目下solr和spring的整合配置詳解

    maven項(xiàng)目下solr和spring的整合配置詳解

    這篇文章主要介紹了maven項(xiàng)目下solr和spring的整合配置詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-11-11
  • SpringBoot對(duì)數(shù)據(jù)訪問(wèn)層進(jìn)行單元測(cè)試的方法詳解

    SpringBoot對(duì)數(shù)據(jù)訪問(wèn)層進(jìn)行單元測(cè)試的方法詳解

    我們公司作為一個(gè)面向銀行、金融機(jī)構(gòu)的TO B類企業(yè),頻繁遇到各個(gè)甲方爸爸提出的國(guó)產(chǎn)化數(shù)據(jù)庫(kù)的改造需求,包括OceanBase, TiDB,geldenDB等等,本文就介紹一種快高效、可復(fù)用的解決方案——對(duì)數(shù)據(jù)訪問(wèn)層做單元測(cè)試,需要的朋友可以參考下
    2023-08-08
  • Springboot+mybatis-plus+注解實(shí)現(xiàn)數(shù)據(jù)權(quán)限隔離

    Springboot+mybatis-plus+注解實(shí)現(xiàn)數(shù)據(jù)權(quán)限隔離

    本文將結(jié)合實(shí)例代碼,介紹Springboot+mybatis-plus+注解實(shí)現(xiàn)數(shù)據(jù)權(quán)限隔離,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-07-07
  • Spring Cloud Ribbon配置詳解

    Spring Cloud Ribbon配置詳解

    這篇文章主要介紹了Spring Cloud Ribbon配置詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • SpringBoot中SmartLifecycle的使用解析

    SpringBoot中SmartLifecycle的使用解析

    這篇文章主要介紹了SpringBoot中SmartLifecycle的使用解析,SmartLifecycle是一個(gè)擴(kuò)展了Lifecycle接口,可以跟蹤spring容器ApplicationContext刷新或者關(guān)閉的接口,實(shí)現(xiàn)該接口的實(shí)現(xiàn)類有特定的執(zhí)行順序,需要的朋友可以參考下
    2023-11-11
  • SpringMVC域?qū)ο蠊蚕頂?shù)據(jù)示例詳解

    SpringMVC域?qū)ο蠊蚕頂?shù)據(jù)示例詳解

    這篇文章主要為大家介紹了SpringMVC域?qū)ο蠊蚕頂?shù)據(jù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • java線程池實(shí)戰(zhàn)應(yīng)用步驟詳解

    java線程池實(shí)戰(zhàn)應(yīng)用步驟詳解

    這篇文章主要介紹了java線程池實(shí)戰(zhàn)應(yīng)用小結(jié),包括線程池的創(chuàng)建方式,本文給大家分享兩種方式,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧
    2025-04-04
  • SpringBoot整合Apollo配置中心快速使用詳解

    SpringBoot整合Apollo配置中心快速使用詳解

    本文主要介紹了SpringBoot整合Apollo配置中心快速使用詳解,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • 詳解Java中布隆過(guò)濾器(Bloom Filter)原理及其使用場(chǎng)景

    詳解Java中布隆過(guò)濾器(Bloom Filter)原理及其使用場(chǎng)景

    布隆過(guò)濾器是1970年由布隆提出的,它實(shí)際上是一個(gè)很長(zhǎng)的二進(jìn)制向量和一系列隨機(jī)映射函數(shù),它的作用是檢索一個(gè)元素是否存在我們的集合之中,本文給大家詳細(xì)的講解一下布隆過(guò)濾器,感興趣的同學(xué)可以參考閱讀
    2023-05-05

最新評(píng)論

襄城县| 介休市| 盐边县| 始兴县| 许昌县| 浦江县| 堆龙德庆县| 宁都县| 斗六市| 页游| 酉阳| 伊宁市| 徐汇区| 北海市| 南丰县| 博湖县| 莒南县| 武威市| 安泽县| 长沙市| 金阳县| 石棉县| 饶平县| 平江县| 平原县| 文水县| 安远县| 彩票| 阿克苏市| 林芝县| 安多县| 盐津县| 永福县| 高平市| 石狮市| 积石山| 合作市| 长泰县| 江川县| 铁岭县| 鄯善县|