下面列出了java.util.jar.JarFile#getName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
try {
if (jf1.size() != jf2.size()) {
throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
+ " have different number of entries");
}
for (JarEntry elem1 : Collections.list(jf1.entries())) {
JarEntry elem2 = jf2.getJarEntry(elem1.getName());
if (elem2 == null) {
throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
}
if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
throw new Exception("The crc of " + elem1.getName() + " is different.");
}
}
} finally {
jf1.close();
jf2.close();
}
}
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
try {
if (jf1.size() != jf2.size()) {
throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
+ " have different number of entries");
}
for (JarEntry elem1 : Collections.list(jf1.entries())) {
JarEntry elem2 = jf2.getJarEntry(elem1.getName());
if (elem2 == null) {
throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
}
if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
throw new Exception("The crc of " + elem1.getName() + " is different.");
}
}
} finally {
jf1.close();
jf2.close();
}
}
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
try {
if (jf1.size() != jf2.size()) {
throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
+ " have different number of entries");
}
for (JarEntry elem1 : Collections.list(jf1.entries())) {
JarEntry elem2 = jf2.getJarEntry(elem1.getName());
if (elem2 == null) {
throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
}
if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
throw new Exception("The crc of " + elem1.getName() + " is different.");
}
}
} finally {
jf1.close();
jf2.close();
}
}
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
try {
if (jf1.size() != jf2.size()) {
throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
+ " have different number of entries");
}
for (JarEntry elem1 : Collections.list(jf1.entries())) {
JarEntry elem2 = jf2.getJarEntry(elem1.getName());
if (elem2 == null) {
throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
}
if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
throw new Exception("The crc of " + elem1.getName() + " is different.");
}
}
} finally {
jf1.close();
jf2.close();
}
}
/**
* Creates a list of files in a given archive (JAR) file. The root directory path, used to
* represent the files, is set to the input archive file path without the file name extension.
*
* @param archive
* The input archive (JAR) file.
* @return <code>Collection</code> of <code>File</code> objects, representing files in the
* given archive file.
* @throws IOException
* If any I/O exception occurs.
*/
public static Collection<File> createFileList(JarFile archive) throws IOException {
ArrayList<File> listOfFiles = new ArrayList<>();
// set root_dir_path = archive_file_path (w/o file name extension)
int nameEndIndex = archive.getName().lastIndexOf('.');
String rootDirPath = (nameEndIndex > 0) ? archive.getName().substring(0, nameEndIndex)
: archive.getName();
File rootDir = new File(rootDirPath);
// add directories to the list
Enumeration<JarEntry> entries = archive.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
File file = new File(rootDir, entry.getName());
if (!entry.isDirectory())
listOfFiles.add(file);
}
return listOfFiles;
}
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
try {
if (jf1.size() != jf2.size()) {
throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
+ " have different number of entries");
}
for (JarEntry elem1 : Collections.list(jf1.entries())) {
JarEntry elem2 = jf2.getJarEntry(elem1.getName());
if (elem2 == null) {
throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
}
if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
throw new Exception("The crc of " + elem1.getName() + " is different.");
}
}
} finally {
jf1.close();
jf2.close();
}
}
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
try {
if (jf1.size() != jf2.size()) {
throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
+ " have different number of entries");
}
for (JarEntry elem1 : Collections.list(jf1.entries())) {
JarEntry elem2 = jf2.getJarEntry(elem1.getName());
if (elem2 == null) {
throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
}
if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
throw new Exception("The crc of " + elem1.getName() + " is different.");
}
}
} finally {
jf1.close();
jf2.close();
}
}
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
try {
if (jf1.size() != jf2.size()) {
throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
+ " have different number of entries");
}
for (JarEntry elem1 : Collections.list(jf1.entries())) {
JarEntry elem2 = jf2.getJarEntry(elem1.getName());
if (elem2 == null) {
throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
}
if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
throw new Exception("The crc of " + elem1.getName() + " is different.");
}
}
} finally {
jf1.close();
jf2.close();
}
}
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
try {
if (jf1.size() != jf2.size()) {
throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
+ " have different number of entries");
}
for (JarEntry elem1 : Collections.list(jf1.entries())) {
JarEntry elem2 = jf2.getJarEntry(elem1.getName());
if (elem2 == null) {
throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
}
if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
throw new Exception("The crc of " + elem1.getName() + " is different.");
}
}
} finally {
jf1.close();
jf2.close();
}
}
public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory)
throws IOException, URISyntaxException {
File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI());
File destinationFileDirectory = new File(destinationDirectory);
JarFile jarFile = new JarFile(sourceFile);
String fileName = jarFile.getName();
String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
File destinationFile = new File(destinationFileDirectory, fileNameLastPart);
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile));
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
InputStream inputStream = jarFile.getInputStream(jarEntry);
//jarOutputStream.putNextEntry(jarEntry);
//create a new jarEntry to avoid ZipException: invalid jarEntry compressed size
jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName()));
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
jarOutputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
jarOutputStream.flush();
jarOutputStream.closeEntry();
}
jarOutputStream.close();
}
/**
* Creates a list of directories in a given archive (JAR) file. The root directory path, used to
* represent the directories, is set to the input archive file path without the file name
* extension.
*
* @param archive
* The input archive (JAR) file.
* @return <code>Collection</code> of <code>File</code> objects, representing directories in
* the given archive file.
* @throws IOException
* If any I/O exception occurs.
*/
public static Collection<File> createDirList(JarFile archive) throws IOException {
ArrayList<File> listOfDirs = new ArrayList<>();
// set root_dir_path = archive_file_path (w/o file name extension)
int nameEndIndex = archive.getName().lastIndexOf('.');
String rootDirPath = (nameEndIndex > 0) ? archive.getName().substring(0, nameEndIndex)
: archive.getName();
File rootDir = new File(rootDirPath);
// add directories to the list
Enumeration<JarEntry> entries = archive.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
File file = new File(rootDir, entry.getName());
if (entry.isDirectory())
listOfDirs.add(file);
else {
// make sure the parent dir is added
File parentDir = file.getParentFile();
while (!parentDir.equals(rootDir)) {
if (!listOfDirs.contains(parentDir))
listOfDirs.add(parentDir);
parentDir = parentDir.getParentFile();
}
}
}
return listOfDirs;
}
private File getRootJarFile(JarFile jarFile) {
String name = jarFile.getName();
int separator = name.indexOf("!/");
if (separator > 0) {
name = name.substring(0, separator);
}
return new File(name);
}
@Test
public void jarFileToURI() throws IOException {
URL url = CodeSourceUtils.getCodeLocation(Logger.class);
logger.debug("url:{}", url);
JarFile jarFile = new JarFile(url.getFile());
logger.debug("jarFile:{}", jarFile.getName());
File file = new File(jarFile.getName());
logger.debug("url1:{}", file.toURI());
}
/**
* Constructor that allows browsing a given PEAR package without unarchiving it.
*
* @param pearPackage
* The given archived PEAR package to browse.
* @throws IOException if a problem with IO
*/
public PackageBrowser(JarFile pearPackage) throws IOException {
_pearPackage = pearPackage;
_pearFile = new File(pearPackage.getName());
int nameEndIndex = _pearFile.getAbsolutePath().lastIndexOf('.');
// set root dir = PEAR file path (w/o file name extension)
String rootDirPath = (nameEndIndex > 0) ? _pearFile.getAbsolutePath()
.substring(0, nameEndIndex) : _pearFile.getAbsolutePath();
_rootDir = new File(rootDirPath);
_archived = true;
// add directories and files to the lists
_allDirs.addAll(FileUtil.createDirList(pearPackage));
_allFiles.addAll(FileUtil.createFileList(pearPackage));
}
public static void add(JarFile jarfile, JarEntry e, ClassFile cf)
throws ConstantPoolException
{
String realName = SharedSecrets.javaUtilJarAccess().getRealName(jarfile, e);
if (realName.startsWith(META_INF_VERSIONS)) {
int len = META_INF_VERSIONS.length();
int n = realName.indexOf('/', len);
if (n > 0) {
String version = realName.substring(len, n);
assert (Integer.parseInt(version) > 8);
String name = cf.getName().replace('/', '.');
if (nameToVersion.containsKey(name)) {
if (!version.equals(nameToVersion.get(name))) {
throw new MultiReleaseException(
"err.multirelease.version.associated",
name, nameToVersion.get(name), version
);
}
} else {
nameToVersion.put(name, version);
}
} else {
throw new MultiReleaseException("err.multirelease.jar.malformed",
jarfile.getName(), realName);
}
}
}
private String getCurrentJarPath() {
String path = null;
try {
URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation();
JarURLConnection connection = (JarURLConnection) url.openConnection();
JarFile jarFile = connection.getJarFile();
path = jarFile.getName();
} catch (IOException e) {
logger.severe(e.getMessage());
}
return path;
}
public static List<URL> loadJar(String path, URL resource) throws IOException
{
JarURLConnection conn = (JarURLConnection) resource.openConnection();
JarFile jarFile = conn.getJarFile();
Enumeration<JarEntry> entries = jarFile.entries();
List<URL> result = new LinkedList<>();
String p = path;
if (!p.endsWith("/"))
{
p = p + "/";
}
while (entries.hasMoreElements())
{
JarEntry entry = entries.nextElement();
if ((!entry.getName().equals(p)) && (entry.getName().startsWith(p) || entry.getName()
.startsWith("WEB-INF/classes/" + p)))
{
URL url = new URL("jar:"
+ new URL("file", null, jarFile.getName() + "!/" + entry.getName()));
result.add(url);
}
}
return result;
}
public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory)
throws IOException, URISyntaxException {
File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI());
File destinationFileDirectory = new File(destinationDirectory);
JarFile jarFile = new JarFile(sourceFile);
String fileName = jarFile.getName();
String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
File destinationFile = new File(destinationFileDirectory, fileNameLastPart);
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile));
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
InputStream inputStream = jarFile.getInputStream(jarEntry);
//jarOutputStream.putNextEntry(jarEntry);
//create a new jarEntry to avoid ZipException: invalid jarEntry compressed size
jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName()));
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
jarOutputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
jarOutputStream.flush();
jarOutputStream.closeEntry();
}
jarOutputStream.close();
}
private YamlConfiguration getExpansionDescription(JarFile jarFile) throws IllegalStateException, IOException, InvalidConfigurationException {
JarEntry entry = jarFile.getJarEntry("expansion.yml");
if(entry == null) {
String errorMessage = ("Expansion file '" + jarFile.getName() + "' does not contain an expansion.yml file.");
throw new IllegalStateException(errorMessage);
}
InputStream inputStream = jarFile.getInputStream(entry);
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader buffer = new BufferedReader(reader);
YamlConfiguration description = new YamlConfiguration();
description.load(buffer);
return description;
}
private void extractFingerPrints() throws IOException, ClassHierarchyException, ClassNotFoundException {
long starttime = System.currentTimeMillis();
logger.info("Process library: " + libraryFile.getName());
logger.info("Library description:");
for (String desc: libDesc.getDescription())
logger.info(desc);
// create analysis scope and generate class hierarchy
final AnalysisScope scope = AnalysisScope.createJavaAnalysisScope();
JarFile jf = libraryFile.getName().endsWith(".aar")? new AarFile(libraryFile).getJarFile() : new JarFile(libraryFile);
scope.addToScope(ClassLoaderReference.Application, jf);
scope.addToScope(ClassLoaderReference.Primordial, new JarFile(LibScoutConfig.pathToAndroidJar));
IClassHierarchy cha = ClassHierarchyFactory.makeWithRoot(scope);
WalaUtils.getChaStats(cha);
// cleanup tmp files if library input was an .aar file
if (libraryFile.getName().endsWith(".aar")) {
File tmpJar = new File(jf.getName());
tmpJar.delete();
logger.debug(Utils.indent() + "tmp jar-file deleted at " + tmpJar.getName());
}
PackageTree pTree = Profile.generatePackageTree(cha);
if (pTree.getRootPackage() == null) {
logger.warn(Utils.INDENT + "Library contains multiple root packages");
}
List<HashTree> hTrees = Profile.generateHashTrees(cha);
// if hash tree is empty do not dump a profile
if (hTrees.isEmpty() || hTrees.get(0).getNumberOfClasses() == 0) {
logger.error("Empty Hash Tree generated - SKIP");
return;
}
// write profile to disk
serialize(pTree, hTrees);
logger.info("");
logger.info("Processing time: " + Utils.millisecondsToFormattedTime(System.currentTimeMillis() - starttime));
}