2

javaを使用してファイルを既存のjarファイルに置き換えています。新しいファイルを置き換えている間、残りのファイルの変更時刻も現在のタイムスタンプに変更されます。他のファイルの元の変更日時を保持するために何をする必要があるかを教えてください。私はコードを使用しています、

    while (entry != null) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (File f : files) {
            if (f.getName().equals(name)) {
                notInFiles = false;
                break;
            }
        }
                    if (notInFiles) {
            // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry(name));
            // Transfer bytes from the ZIP file to the output file
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }
    // Close the streams        
    zin.close();
    // Compress the files
    for (int i = 0; i < files.length; i++) {
        InputStream in = new FileInputStream(files[i]);
        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(files[i].getName()));
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // Complete the entry
        out.closeEntry();
        in.close();
    }
4

1 に答える 1

1

Jar ファイルは基本的に、異なるファイル タイプの拡張子を持つ zip ファイルであるため、ZipFileSystemProviderを使用して、jar ファイルをjava.nio.file.FileSystemとしてマウントできます。

次に、Files.copy(fromPath,toPath,replace)を使用してファイルをコピーします。これにより、jar 内の他のファイルはそのまま残り、おそらくはるかに高速になります。

public class Zipper {

    public static void main(String [] args) throws Throwable {
        Path zipPath = Paths.get("c:/test.jar");

        //Mount the zipFile as a FileSysten
        try (FileSystem zipfs = FileSystems.newFileSystem(zipPath,null)) {

            //Setup external and internal paths
            Path externalTxtFile = Paths.get("c:/test1.txt");
            Path pathInZipfile = zipfs.getPath("/test1.txt");          

            //Copy the external file into the zipfile, Copy option to force overwrite if already exists
            Files.copy(externalTxtFile, pathInZipfile,StandardCopyOption.REPLACE_EXISTING);

            //Close the ZipFileSystem
            zipfs.close();
        } 
    }
}
于 2013-01-10T10:11:45.320 に答える