首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >`File#list`什么时候可以使用Windows文件夹?

`File#list`什么时候可以使用Windows文件夹?
EN

Stack Overflow用户
提问于 2018-04-13 09:34:04
回答 1查看 27关注 0票数 0

我有一些Java代码可以做到这一点(在Windows 10笔记本电脑上有Windows Defender on):

  • 将.zip文件解压缩到文件夹中(使用压缩流)
  • 立即列出文件夹的内容(使用File#list)

在zip中有10个文件,从100 to到40 to不等。通常,只列出前两个文件--其他8个文件会悄悄丢失。我知道他们实际上能够到达目录,因为当我自己导航到目录时,我可以看到它们。

我知道有更好的方法来实现这段代码,但我很好奇:这是预期的吗?“将文件写入文件夹”和“在列出文件夹内容时列出文件”在Windows上不是原子的吗?这是底层文件系统的怪癖吗?在写完文件之后,Windows保护程序是否会使文件在一段时间内不可见?

EN

回答 1

Stack Overflow用户

发布于 2018-04-13 11:29:17

我没有面对您提到的问题,我的代码能够正确列出所有文件:

代码语言:javascript
运行
复制
package com.test;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipTest {

    private static final int BUFFER_SIZE = 4096;

    private static String INPUT_LOCATION = "C:/temp/zip/test.zip";
    private static String OUTPUT_LOCATION = "C:/temp/unzip";

    public static void main(String[] args) throws IOException {
        unzip(INPUT_LOCATION, OUTPUT_LOCATION);
        for (String s : new File(OUTPUT_LOCATION).list()) {
            System.out.println(s);
        }
    }

    public static void unzip(String zipFilePath, String destDirectory) throws IOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry entry = zipIn.getNextEntry();

        while (entry != null) {
            String filePath = destDirectory + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                extractFile(zipIn, filePath);
            } else {
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    }

    private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[BUFFER_SIZE];
        int read = 0;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49813746

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档