如何使用TrueVFS for java通过路径访问文件?

时间:2014-06-01 20:06:47

标签: java saving-data truevfs

这是我的代码。

/**
 * Load an Object from disk.
 */
public static <T> T load(String path) throws IOException {
    File entry = new TFile(path);
    char[] chars = new char[(int)entry.length()];
    InputStream in = new TFileInputStream(entry);
    BufferedReader fIn = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    fIn.read(chars);
    fIn.close();
    //converts the string to an object using the Base64Coder
    return decode(new String(chars));
}


/**
 * Save an object to disk as a compressed file.
 */
public static void save(String path, Serializable o) {
    //converts the object to a string
    String content = encode(o);
    File entry = new TFile(path);
    Writer writer;
    try {
        writer = new TFileWriter(entry);
        writer.write(content);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我尝试使用TrueVFS将内存中的对象加载并保存到压缩文件中。 此代码在此处有效,但仅在我直接引用文件时才有效。 (所以给出的路径类似于&#34; data.zip/data Entries / 0/2 / data.txt&#34;)

我遇到的问题是,只要我尝试将此文件放入路径(因此给出的路径类似于&#34;保存文件/世界1 / data.zip / dataEntry / 0/2 / data .txt&#34;),我收到NoSuchFileException错误。

我应该如何将档案放入指定的文件夹?

1 个答案:

答案 0 :(得分:0)

解决了问题,这里是新代码。

/**
 * Load an Object from disk.
 */
public static <T> T load(String directory, String fileName, String archiveDirectory) throws IOException {
    File entry = new TFile(directory + fileName, archiveDirectory);
    char[] chars = new char[(int)entry.length()];
    InputStream in = new TFileInputStream(entry);
    BufferedReader fIn = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    fIn.read(chars);
    fIn.close();
    return decode(new String(chars));
}


/**
 * Save an object to disk as a compressed file.
 */
public static void save(String directory, String fileName, String archiveDirectory, Serializable o) {
    String content = encode(o);
    Path parent = new TPath(directory);
    Writer writer;
    try {
        if (!Files.exists(parent)) {
            Files.createDirectory(parent);
        }
        File entry = new TFile(directory + fileName, archiveDirectory);
        writer = new TFileWriter(entry);
        writer.write(content);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}