下面列出了java.util.jar.JarEntry#setTime ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Writes a new {@link File} into the archive.
* @param inputFile the {@link File} to write.
* @param jarPath the filepath inside the archive.
* @throws IOException
*/
public void writeFile(File inputFile, String jarPath) throws IOException {
// Get an input stream on the file.
FileInputStream fis = new FileInputStream(inputFile);
try {
// create the zip entry
JarEntry entry = new JarEntry(jarPath);
entry.setTime(inputFile.lastModified());
writeEntry(fis, entry);
} finally {
// close the file stream used to read the file
fis.close();
}
}
/**
* Writes a new {@link File} into the archive.
* @param inputFile the {@link File} to write.
* @param jarPath the filepath inside the archive.
* @throws IOException
*/
public void writeFile(File inputFile, String jarPath) throws IOException {
// Get an input stream on the file.
FileInputStream fis = new FileInputStream(inputFile);
try {
// create the zip entry
JarEntry entry = new JarEntry(jarPath);
entry.setTime(inputFile.lastModified());
writeEntry(fis, entry);
} finally {
// close the file stream used to read the file
fis.close();
}
}
static public void setEntryTime (String inJar, String outJar, long time) throws IOException {
if (DEBUG) debug("scar", "Setting entry to for JAR: " + inJar + " -> " + outJar + ", " + time);
JarFile inJarFile = new JarFile(inJar);
mkdir(parent(outJar));
JarOutputStream outJarStream = new JarOutputStream(new FileOutputStream(outJar));
outJarStream.setLevel(Deflater.BEST_COMPRESSION);
for (Enumeration<JarEntry> entries = inJarFile.entries(); entries.hasMoreElements();) {
JarEntry inEntry = entries.nextElement();
String name = inEntry.getName();
JarEntry outEntry = new JarEntry(name);
outEntry.setTime(time);
outJarStream.putNextEntry(outEntry);
copyStream(inJarFile.getInputStream(inEntry), outJarStream);
outJarStream.closeEntry();
}
outJarStream.close();
inJarFile.close();
}
/**
* Writes a new {@link File} into the archive.
*
* @param inputFile the {@link File} to write.
* @param jarPath the filepath inside the archive.
* @throws IOException
*/
public void writeFile(File inputFile, String jarPath) throws IOException {
// Get an input stream on the file.
FileInputStream fis = new FileInputStream(inputFile);
try {
// create the zip entry
JarEntry entry = new JarEntry(jarPath);
entry.setTime(inputFile.lastModified());
writeEntry(fis, entry);
} finally {
// close the file stream used to read the file
fis.close();
}
}
public static void addFileToJar(JarOutputStream jar, File source, String entryName) throws IOException {
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source))) {
JarEntry entry = new JarEntry(entryName);
entry.setTime(source.lastModified());
jar.putNextEntry(entry);
copyStream(in, jar);
jar.closeEntry();
}
}
private static void addEntry(JarOutputStream jos, String name, byte[] bytes) throws IOException {
JarEntry je = new JarEntry(name);
// TODO(cushon): switch to setLocalTime after we migrate to JDK 9
je.setTime(DEFAULT_TIMESTAMP);
je.setMethod(ZipEntry.STORED);
je.setSize(bytes.length);
je.setCrc(Hashing.crc32().hashBytes(bytes).padToLong());
jos.putNextEntry(je);
jos.write(bytes);
}
/**
* Creates a new JarEntry with the passed path and contents, and writes it
* to the current archive.
*
* @param resource the file to write
* @param path the path inside the archive
*
* @throws IOException if an I/O error has occurred
* @throws CoreException if the resource can-t be accessed
*/
protected void addFile(IFile resource, IPath path) throws IOException, CoreException {
JarEntry newEntry= new JarEntry(path.toString().replace(File.separatorChar, '/'));
byte[] readBuffer= new byte[4096];
if (fJarPackage.isCompressed())
newEntry.setMethod(ZipEntry.DEFLATED);
// Entry is filled automatically.
else {
newEntry.setMethod(ZipEntry.STORED);
JarPackagerUtil.calculateCrcAndSize(newEntry, resource.getContents(false), readBuffer);
}
long lastModified= System.currentTimeMillis();
URI locationURI= resource.getLocationURI();
if (locationURI != null) {
IFileInfo info= EFS.getStore(locationURI).fetchInfo();
if (info.exists())
lastModified= info.getLastModified();
}
// Set modification time
newEntry.setTime(lastModified);
InputStream contentStream = resource.getContents(false);
addEntry(newEntry, contentStream);
}
/**
* Add the directory entries for the given path to the jar.
*
* @param destinationPath the path to add
* @param correspondingFile the corresponding file in the file system
* or <code>null</code> if it doesn't exist
* @throws IOException if an I/O error has occurred
*/
private void addDirectories(IPath destinationPath, File correspondingFile) throws IOException {
String path= destinationPath.toString().replace(File.separatorChar, '/');
int lastSlash= path.lastIndexOf('/');
List<JarEntry> directories= new ArrayList<JarEntry>(2);
while(lastSlash != -1) {
path= path.substring(0, lastSlash + 1);
if (!fDirectories.add(path))
break;
if (correspondingFile != null)
correspondingFile= correspondingFile.getParentFile();
long timeStamp= correspondingFile != null && correspondingFile.exists()
? correspondingFile.lastModified()
: System.currentTimeMillis();
JarEntry newEntry= new JarEntry(path);
newEntry.setMethod(ZipEntry.STORED);
newEntry.setSize(0);
newEntry.setCrc(0);
newEntry.setTime(timeStamp);
directories.add(newEntry);
lastSlash= path.lastIndexOf('/', lastSlash - 1);
}
for(int i= directories.size() - 1; i >= 0; --i) {
fJarOutputStream.putNextEntry(directories.get(i));
}
}
public static void addFileToJar(JarOutputStream jar, File source, String entryName) throws IOException {
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source))) {
JarEntry entry = new JarEntry(entryName);
entry.setTime(source.lastModified());
jar.putNextEntry(entry);
copyStream(in, jar);
jar.closeEntry();
}
}
/**
* Creates a new JarEntry with the passed path and contents, and writes it
* to the current archive.
*
* @param path the path inside the archive
* @param contents the bytes to write
* @param lastModified a long which represents the last modification date
* @throws IOException if an I/O error has occurred
*/
protected void write(IPath path, byte[] contents, long lastModified) throws IOException {
JarEntry newEntry= new JarEntry(path.toString().replace(File.separatorChar, '/'));
if (fJarPackage.isCompressed())
newEntry.setMethod(ZipEntry.DEFLATED);
// Entry is filled automatically.
else {
newEntry.setMethod(ZipEntry.STORED);
newEntry.setSize(contents.length);
CRC32 checksumCalculator= new CRC32();
checksumCalculator.update(contents);
newEntry.setCrc(checksumCalculator.getValue());
}
// Set modification time
newEntry.setTime(lastModified);
try {
fJarOutputStream.putNextEntry(newEntry);
fJarOutputStream.write(contents);
} finally {
/*
* Commented out because some JREs throw an NPE if a stream
* is closed twice. This works because
* a) putNextEntry closes the previous entry
* b) closing the stream closes the last entry
*/
// fJarOutputStream.closeEntry();
}
}
private static JarEntry smartClone(JarEntry originalJarEntry) {
final JarEntry newJarEntry = new JarEntry(originalJarEntry.getName());
newJarEntry.setComment(originalJarEntry.getComment());
newJarEntry.setExtra(originalJarEntry.getExtra());
newJarEntry.setMethod(originalJarEntry.getMethod());
newJarEntry.setTime(originalJarEntry.getTime());
//Must set size and CRC for STORED entries
if (newJarEntry.getMethod() == ZipEntry.STORED) {
newJarEntry.setSize(originalJarEntry.getSize());
newJarEntry.setCrc(originalJarEntry.getCrc());
}
return newJarEntry;
}
private void saveClassToStream(String qualifiedClassName, byte[] bytes) throws IOException {
// Convert this fully-qualified name into an internal name, since that is the serialized name it needs.
String internalName = Utilities.fulllyQualifiedNameToInternalName(qualifiedClassName);
if (this.entriesInJar.contains(internalName)) {
// This is a static usage error.
throw new AssertionError("Added class to JAR twice");
}
JarEntry entry = new JarEntry(internalName + ".class");
// AKI-135: While we only use this utility in tests, it is still convenient if we force the timestamp for deterministic JAR creation.
entry.setTime(FIXED_TIMESTAMP);
this.jarStream.putNextEntry(entry);
this.jarStream.write(bytes);
this.jarStream.closeEntry();
this.entriesInJar.add(internalName);
}
private static void createTestJar(OutputStream outStream, String dummyClassName)
throws URISyntaxException, IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaFileObject srcFileObject = new SimpleJavaFileObjectImpl(
URI.create("string:///" + dummyClassName + Kind.SOURCE.extension), Kind.SOURCE);
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
compiler.getTask(null, fileManager, null, null, null, Collections.singletonList(srcFileObject))
.call();
JavaFileObject javaFileObject = fileManager.getJavaFileForOutput(StandardLocation.CLASS_OUTPUT,
dummyClassName, Kind.CLASS, null);
File classFile = new File(dummyClassName + Kind.CLASS.extension);
JarOutputStream jarOutputStream = new JarOutputStream(outStream);
JarEntry jarEntry = new JarEntry(classFile.getName());
jarEntry.setTime(classFile.lastModified());
jarOutputStream.putNextEntry(jarEntry);
InputStream in = javaFileObject.openInputStream();
byte buffer[] = new byte[4096];
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
jarOutputStream.write(buffer, 0, nRead);
}
in.close();
jarOutputStream.close();
javaFileObject.delete();
}
private JarEntry createJarEntry(Path source) throws IOException {
String entryName = FilenameUtils.separatorsToUnix(mtaAssemblyDir.relativize(source)
.toString());
if (source.toFile()
.isDirectory()
&& !entryName.endsWith(Constants.UNIX_PATH_SEPARATOR)) {
entryName += Constants.UNIX_PATH_SEPARATOR;
}
JarEntry entry = new JarEntry(entryName);
entry.setTime(Files.getLastModifiedTime(source)
.toMillis());
return entry;
}
/**
* Recursively jars up the given path under the given directory.
*/
private void jarDir(File dirOrFile2jar, JarOutputStream jos, String path)
throws IOException {
if (mVerbose) {
System.out.println("checking " + dirOrFile2jar);
}
if (dirOrFile2jar.isDirectory()) {
String[] dirList = dirOrFile2jar.list();
String subPath = (path == null) ? "" : (path + dirOrFile2jar.getName() + SEP);
if (path != null) {
JarEntry je = new JarEntry(subPath);
je.setTime(dirOrFile2jar.lastModified());
jos.putNextEntry(je);
jos.flush();
jos.closeEntry();
}
for (int i = 0; i < dirList.length; i++) {
File f = new File(dirOrFile2jar, dirList[i]);
jarDir(f, jos, subPath);
}
} else if (dirOrFile2jar.exists()) {
if (dirOrFile2jar.getCanonicalPath().equals(mDestJarName)) {
if (mVerbose) {
System.out.println("skipping " + dirOrFile2jar.getPath());
}
return;
}
if (mVerbose) {
System.out.println("adding " + dirOrFile2jar.getPath());
}
FileInputStream fis = new FileInputStream(dirOrFile2jar);
try {
JarEntry entry = new JarEntry(path + dirOrFile2jar.getName());
entry.setTime(dirOrFile2jar.lastModified());
jos.putNextEntry(entry);
while ((mByteCount = fis.read(mBuffer)) != -1) {
jos.write(mBuffer, 0, mByteCount);
if (mVerbose) {
System.out.println("wrote " + mByteCount + " bytes");
}
}
jos.flush();
jos.closeEntry();
} catch (IOException ioe) {
throw ioe;
} finally {
fis.close();
}
}
}
/**
* Recursively jars up the given path under the given directory.
*/
private void jarDir(File dirOrFile2jar, JarOutputStream jos, String path)
throws IOException {
if (mVerbose) {
System.out.println("checking " + dirOrFile2jar);
}
if (dirOrFile2jar.isDirectory()) {
String[] dirList = dirOrFile2jar.list();
String subPath = (path == null) ? "" : (path + dirOrFile2jar.getName() + SEP);
if (path != null) {
JarEntry je = new JarEntry(subPath);
je.setTime(dirOrFile2jar.lastModified());
jos.putNextEntry(je);
jos.flush();
jos.closeEntry();
}
for (int i = 0; i < dirList.length; i++) {
File f = new File(dirOrFile2jar, dirList[i]);
jarDir(f, jos, subPath);
}
} else if (dirOrFile2jar.exists()) {
if (dirOrFile2jar.getCanonicalPath().equals(mDestJarName)) {
if (mVerbose) {
System.out.println("skipping " + dirOrFile2jar.getPath());
}
return;
}
if (mVerbose) {
System.out.println("adding " + dirOrFile2jar.getPath());
}
FileInputStream fis = new FileInputStream(dirOrFile2jar);
try {
JarEntry entry = new JarEntry(path + dirOrFile2jar.getName());
entry.setTime(dirOrFile2jar.lastModified());
jos.putNextEntry(entry);
while ((mByteCount = fis.read(mBuffer)) != -1) {
jos.write(mBuffer, 0, mByteCount);
if (mVerbose) {
System.out.println("wrote " + mByteCount + " bytes");
}
}
jos.flush();
jos.closeEntry();
} catch (IOException ioe) {
throw ioe;
} finally {
fis.close();
}
}
}
private void unpackSegment(InputStream in, JarOutputStream out) throws IOException {
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"0");
// Process the output directory or jar output.
new PackageReader(pkg, in).read();
if (props.getBoolean("unpack.strip.debug")) pkg.stripAttributeKind("Debug");
if (props.getBoolean("unpack.strip.compile")) pkg.stripAttributeKind("Compile");
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"50");
pkg.ensureAllClassFiles();
// Now write out the files.
Set<Package.Class> classesToWrite = new HashSet<>(pkg.getClasses());
for (Package.File file : pkg.getFiles()) {
String name = file.nameString;
JarEntry je = new JarEntry(Utils.getJarEntryName(name));
boolean deflate;
deflate = (keepDeflateHint)
? (((file.options & Constants.FO_DEFLATE_HINT) != 0) ||
((pkg.default_options & Constants.AO_DEFLATE_HINT) != 0))
: deflateHint;
boolean needCRC = !deflate; // STORE mode requires CRC
if (needCRC) crc.reset();
bufOut.reset();
if (file.isClassStub()) {
Package.Class cls = file.getStubClass();
assert(cls != null);
new ClassWriter(cls, needCRC ? crcOut : bufOut).write();
classesToWrite.remove(cls); // for an error check
} else {
// collect data & maybe CRC
file.writeTo(needCRC ? crcOut : bufOut);
}
je.setMethod(deflate ? JarEntry.DEFLATED : JarEntry.STORED);
if (needCRC) {
if (verbose > 0)
Utils.log.info("stored size="+bufOut.size()+" and crc="+crc.getValue());
je.setMethod(JarEntry.STORED);
je.setSize(bufOut.size());
je.setCrc(crc.getValue());
}
if (keepModtime) {
je.setTime(file.modtime);
// Convert back to milliseconds
je.setTime((long)file.modtime * 1000);
} else {
je.setTime((long)modtime * 1000);
}
out.putNextEntry(je);
bufOut.writeTo(out);
out.closeEntry();
if (verbose > 0)
Utils.log.info("Writing "+Utils.zeString((ZipEntry)je));
}
assert(classesToWrite.isEmpty());
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"100");
pkg.reset(); // reset for the next segment, if any
}
private void unpackSegment(InputStream in, JarOutputStream out) throws IOException {
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"0");
// Process the output directory or jar output.
new PackageReader(pkg, in).read();
if (props.getBoolean("unpack.strip.debug")) pkg.stripAttributeKind("Debug");
if (props.getBoolean("unpack.strip.compile")) pkg.stripAttributeKind("Compile");
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"50");
pkg.ensureAllClassFiles();
// Now write out the files.
Set<Package.Class> classesToWrite = new HashSet<>(pkg.getClasses());
for (Package.File file : pkg.getFiles()) {
String name = file.nameString;
JarEntry je = new JarEntry(Utils.getJarEntryName(name));
boolean deflate;
deflate = (keepDeflateHint)
? (((file.options & Constants.FO_DEFLATE_HINT) != 0) ||
((pkg.default_options & Constants.AO_DEFLATE_HINT) != 0))
: deflateHint;
boolean needCRC = !deflate; // STORE mode requires CRC
if (needCRC) crc.reset();
bufOut.reset();
if (file.isClassStub()) {
Package.Class cls = file.getStubClass();
assert(cls != null);
new ClassWriter(cls, needCRC ? crcOut : bufOut).write();
classesToWrite.remove(cls); // for an error check
} else {
// collect data & maybe CRC
file.writeTo(needCRC ? crcOut : bufOut);
}
je.setMethod(deflate ? JarEntry.DEFLATED : JarEntry.STORED);
if (needCRC) {
if (verbose > 0)
Utils.log.info("stored size="+bufOut.size()+" and crc="+crc.getValue());
je.setMethod(JarEntry.STORED);
je.setSize(bufOut.size());
je.setCrc(crc.getValue());
}
if (keepModtime) {
je.setTime(file.modtime);
// Convert back to milliseconds
je.setTime((long)file.modtime * 1000);
} else {
je.setTime((long)modtime * 1000);
}
out.putNextEntry(je);
bufOut.writeTo(out);
out.closeEntry();
if (verbose > 0)
Utils.log.info("Writing "+Utils.zeString((ZipEntry)je));
}
assert(classesToWrite.isEmpty());
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"100");
pkg.reset(); // reset for the next segment, if any
}
private void unpackSegment(InputStream in, JarOutputStream out) throws IOException {
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"0");
// Process the output directory or jar output.
new PackageReader(pkg, in).read();
if (props.getBoolean("unpack.strip.debug")) pkg.stripAttributeKind("Debug");
if (props.getBoolean("unpack.strip.compile")) pkg.stripAttributeKind("Compile");
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"50");
pkg.ensureAllClassFiles();
// Now write out the files.
Set<Package.Class> classesToWrite = new HashSet<>(pkg.getClasses());
for (Package.File file : pkg.getFiles()) {
String name = file.nameString;
JarEntry je = new JarEntry(Utils.getJarEntryName(name));
boolean deflate;
deflate = (keepDeflateHint)
? (((file.options & Constants.FO_DEFLATE_HINT) != 0) ||
((pkg.default_options & Constants.AO_DEFLATE_HINT) != 0))
: deflateHint;
boolean needCRC = !deflate; // STORE mode requires CRC
if (needCRC) crc.reset();
bufOut.reset();
if (file.isClassStub()) {
Package.Class cls = file.getStubClass();
assert(cls != null);
new ClassWriter(cls, needCRC ? crcOut : bufOut).write();
classesToWrite.remove(cls); // for an error check
} else {
// collect data & maybe CRC
file.writeTo(needCRC ? crcOut : bufOut);
}
je.setMethod(deflate ? JarEntry.DEFLATED : JarEntry.STORED);
if (needCRC) {
if (verbose > 0)
Utils.log.info("stored size="+bufOut.size()+" and crc="+crc.getValue());
je.setMethod(JarEntry.STORED);
je.setSize(bufOut.size());
je.setCrc(crc.getValue());
}
if (keepModtime) {
je.setTime(file.modtime);
// Convert back to milliseconds
je.setTime((long)file.modtime * 1000);
} else {
je.setTime((long)modtime * 1000);
}
out.putNextEntry(je);
bufOut.writeTo(out);
out.closeEntry();
if (verbose > 0)
Utils.log.info("Writing "+Utils.zeString((ZipEntry)je));
}
assert(classesToWrite.isEmpty());
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"100");
pkg.reset(); // reset for the next segment, if any
}
private void unpackSegment(InputStream in, JarOutputStream out) throws IOException {
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"0");
// Process the output directory or jar output.
new PackageReader(pkg, in).read();
if (props.getBoolean("unpack.strip.debug")) pkg.stripAttributeKind("Debug");
if (props.getBoolean("unpack.strip.compile")) pkg.stripAttributeKind("Compile");
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"50");
pkg.ensureAllClassFiles();
// Now write out the files.
Set<Package.Class> classesToWrite = new HashSet<>(pkg.getClasses());
for (Package.File file : pkg.getFiles()) {
String name = file.nameString;
JarEntry je = new JarEntry(Utils.getJarEntryName(name));
boolean deflate;
deflate = (keepDeflateHint)
? (((file.options & Constants.FO_DEFLATE_HINT) != 0) ||
((pkg.default_options & Constants.AO_DEFLATE_HINT) != 0))
: deflateHint;
boolean needCRC = !deflate; // STORE mode requires CRC
if (needCRC) crc.reset();
bufOut.reset();
if (file.isClassStub()) {
Package.Class cls = file.getStubClass();
assert(cls != null);
new ClassWriter(cls, needCRC ? crcOut : bufOut).write();
classesToWrite.remove(cls); // for an error check
} else {
// collect data & maybe CRC
file.writeTo(needCRC ? crcOut : bufOut);
}
je.setMethod(deflate ? JarEntry.DEFLATED : JarEntry.STORED);
if (needCRC) {
if (verbose > 0)
Utils.log.info("stored size="+bufOut.size()+" and crc="+crc.getValue());
je.setMethod(JarEntry.STORED);
je.setSize(bufOut.size());
je.setCrc(crc.getValue());
}
if (keepModtime) {
je.setTime(file.modtime);
// Convert back to milliseconds
je.setTime((long)file.modtime * 1000);
} else {
je.setTime((long)modtime * 1000);
}
out.putNextEntry(je);
bufOut.writeTo(out);
out.closeEntry();
if (verbose > 0)
Utils.log.info("Writing "+Utils.zeString((ZipEntry)je));
}
assert(classesToWrite.isEmpty());
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"100");
pkg.reset(); // reset for the next segment, if any
}