-->

Java: `A` Archive attribute missing while creating

2019-02-28 06:50发布

问题:

We are dealing with the decompression libraries/utility that uses attribute to check for the presence of directories/files within the zip.

Problem is that we are not able to set archive bit for a zip while creation. When we create zip programmatically, it wash out previous attributes as well.

We will try to set archive bit with below mentioned steps but not getting desired result so far:

1. Parse each zip entry and getExtra byte[].
2. Use Int value=32 and perform bitwise 'OR' operation.
3. setExtra byte[] after 'OR' operation.

Adding some more details: We tried following approaches but still this issue is unresolved.

  1. Using setAttribute() method on File system but getting the attributes are getting reset while creating zip. Files.setAttribute(file, “dos:archive”, true)

  2. Using File.copy() which copies the file attributes associated with the file to the target file but no success. Even existing attributes are not being retained to target file. Files.copy(path, path, StandardCopyOption.COPY_ATTRIBUTES)

  3. Using ZipEntry.setExtra(byte[]). found some info online that the java doesn’t have any direct method to set attributes but as per some online articles we found that the extra field is used to set the file permissions on unix and MS DOS file attributes. This is an undocumented field and we didn’t find any reliable information online. Basically, initial 2 bytes are used for unix and last 2 bytes are used for DOS file attributes. We tried setting DOS file attributes with different values in it. ZipEntry.setExtra(byte[]) - Sets the optional extra field data for the entry.

  4. Using winzip command line tool but not an elegant solution.

回答1:

I assume it is DOS (Windows)

With Java 7

import java.nio.file.Files;
import java.nio.file.Path;

File theFile = new File("yourfile.zip");
Path file = theFile.toPath();
Files.setAttribute(file, "dos:archive", true);

see: http://kodejava.org/how-do-i-set-the-value-of-file-attributes/