FileNotFoundException(没有这样的文件或目录)

时间:2012-06-18 14:20:12

标签: java java-io

我正在编写一个Android应用程序,我需要从几个文件夹中读取几个文件并将它们添加到多个zip存档中。我需要限制档案的最大大小,比方说16mb。因此,在运行时,如果文件的大小超过16 mb,则将文件添加到存档,创建另一个具有相同大小限制的存档,依此类推。我正在使用以下包装类:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ChunkedZippedOutputStream {
    private ZipOutputStream zipOutputStream;

    private String path;

    private String name;

    private long currentSize;

    private int currentChunkIndex;

    private final long MAX_FILE_SIZE = 16 * 1000 * 1024; // 16mb limit

    private final String PART_POSTFIX = ".part";

    private final String FILE_EXTENSION = ".zip";

    public ChunkedZippedOutputStream(String path, String name) throws FileNotFoundException {
        this.path = path;
        this.name = name;
        constructNewStream();
    }

    public void addEntry(ZipEntry entry) throws IOException {
        long entrySize = entry.getCompressedSize();
        if ((currentSize + entrySize) > MAX_FILE_SIZE) {
            closeStream();
            constructNewStream();
        } else {
            currentSize += entrySize;
            zipOutputStream.putNextEntry(entry);
        }
    }

    private void closeStream() throws IOException {
        zipOutputStream.close();
    }

    private void constructNewStream() throws FileNotFoundException {
        zipOutputStream = new ZipOutputStream(new FileOutputStream(new File(path, constructCurrentPartName())));
        currentChunkIndex++;
        currentSize = 0;
    }

    private String constructCurrentPartName() {
        // This will give names is the form of <file_name>.part.0.zip, <file_name>.part.1.zip, etc.
        StringBuilder partNameBuilder = new StringBuilder(name);
        partNameBuilder.append(PART_POSTFIX);
        partNameBuilder.append(currentChunkIndex);
        partNameBuilder.append(FILE_EXTENSION);
        return partNameBuilder.toString();
    }
}

我这样用它:

String zipPath = Environment.getExternalStorageDirectory() + "/MyApp/MyFolder/Zip/";
String zipName = "MyZipFle";
ChunkedZippedOutputStream zippedOutputStream = new ChunkedZippedOutputStream(zipPath, zipName);
....
zippedOutputStream.addEntry(new ZipEntry("ZipEntry" + i));

但是ChunkedZippedOutputStream对象的实例化我得到了这个错误:

  java.io.FileNotFoundException: /mnt/sdcard/MyApp/MyFolder/Zip/MyZipFle.part0.zip (No such file or directory)

我知道我对路径输入或名称做错了但是我无法弄清楚是什么。

此外,如果代码段不正确,请告诉我,我从这里得到它How to split a huge zip file into multiple volumes?

如果我的问题有一个更简单的解决方案,请告诉我。谢谢

2 个答案:

答案 0 :(得分:7)

输出目录不存在。有关解决方案,请参阅File.mkdirs(),

答案 1 :(得分:0)

这对我有用

Project
|->src
|   |-->MyClass.java
|   |-->MyFile1.txt
|->res
   |->files
     |-->MyFile2.txt

示例:

对于MyFile1,您可以使用新的File(“ MyFile1.txt”);
   对于MyFile2,您可以使用新的File(“ ./ res / files / MyFile2.txt”);