-
Notifications
You must be signed in to change notification settings - Fork 53
io microsphere util jar JarUtils
Type: Class | Module: microsphere-java-core | Package: io.microsphere.util.jar | Since: 1.0.0
Source:
microsphere-java-core/src/main/java/io/microsphere/util/jar/JarUtils.java
Jar Utility class
public abstract class JarUtils implements UtilsAuthor: Mercy
-
Introduced in:
1.0.0 -
Current Project Version:
0.2.8-SNAPSHOT
This component is tested and compatible with the following Java versions:
| Java Version | Status |
|---|---|
| Java 8 | ✅ Compatible |
| Java 11 | ✅ Compatible |
| Java 17 | ✅ Compatible |
| Java 21 | ✅ Compatible |
| Java 25 | ✅ Compatible |
URL jarURL = new URL("jar:file:/path/to/file.jar!/entry");
JarFile jarFile = JarUtils.toJarFile(jarURL);URL jarURL = new URL("jar:file:/path/to/file.jar!/com/example/resource.txt");
String relativePath = JarUtils.resolveRelativePath(jarURL);
System.out.println(relativePath); // Output: com/example/resource.txtURL jarURL = new URL("jar:file:/path/to/file.jar!/com/example/resource.txt");
String absolutePath = JarUtils.resolveJarAbsolutePath(jarURL);
System.out.println(absolutePath); // Output: /path/to/file.jarJarFile jarFile = new JarFile("example.jar");
JarEntryFilter classFileFilter = entry -> entry.getName().endsWith(".class");
List<JarEntry> filteredEntries = JarUtils.filter(jarFile, classFileFilter);List<JarEntry> entries = // ... obtain jar entries
JarEntryFilter filter = entry -> entry.getName().endsWith(".xml");
List<JarEntry> filtered = JarUtils.doFilter(entries, filter);URL jarURL = new URL("jar:file:/path/to/file.jar!/com/example/resource.txt");
JarEntry jarEntry = JarUtils.findJarEntry(jarURL);
System.out.println(jarEntry.getName()); // Output: com/example/resource.txtFile jarFile = new File("example.jar");
File outputDir = new File("/path/to/output");
JarUtils.extract(jarFile, outputDir);File jarFile = new File("example.jar");
File outputDir = new File("/path/to/output");
// Extract all entries
JarUtils.extract(jarFile, outputDir, null);
// Extract only .class files
JarEntryFilter classFileFilter = entry -> entry.getName().endsWith(".class");
JarUtils.extract(jarFile, outputDir, classFileFilter);JarFile jarFile = new JarFile("example.jar");
File outputDir = new File("/path/to/output");
// Extract all entries
JarUtils.extract(jarFile, outputDir, null);
// Extract only .class files
JarEntryFilter classFileFilter = entry -> entry.getName().endsWith(".class");
JarUtils.extract(jarFile, outputDir, classFileFilter);URL jarURL = new URL("jar:file:/path/to/file.jar!/com/example/");
File outputDir = new File("/path/to/output");
// Extract all entries under 'com/example/'
JarUtils.extract(jarURL, outputDir, null);
// Extract only .class files under 'com/example/'
JarEntryFilter classFileFilter = entry -> entry.getName().endsWith(".class");
JarUtils.extract(jarURL, outputDir, classFileFilter);URL jarURL = new URL("jar:file:/path/to/file.jar!/");
boolean isDirectory = JarUtils.isDirectoryEntry(jarURL);
System.out.println(isDirectory); // Output: true
URL fileURL = new URL("jar:file:/path/to/file.jar!/com/example/");
isDirectory = JarUtils.isDirectoryEntry(fileURL);
System.out.println(isDirectory); // Output: true
URL resourceURL = new URL("jar:file:/path/to/file.jar!/com/example/resource.txt");
isDirectory = JarUtils.isDirectoryEntry(resourceURL);
System.out.println(isDirectory); // Output: falseAdd the following dependency to your pom.xml:
<dependency>
<groupId>io.github.microsphere-projects</groupId>
<artifactId>microsphere-java-core</artifactId>
<version>${microsphere-java.version}</version>
</dependency>Tip: Use the BOM (
microsphere-java-dependencies) for consistent version management. See the Getting Started guide.
import io.microsphere.util.jar.JarUtils;| Method | Description |
|---|---|
toJarFile |
The resource path of Manifest file in JAR archive. |
resolveRelativePath |
Assert jarURL argument is valid , only supported protocols : ProtocolConstants#JAR_PROTOCOL jar and |
resolveJarAbsolutePath |
Resolves the absolute path of the JAR file from the provided URL. |
filter |
Filters the entries of a JAR file based on the provided JarEntryFilter. |
findJarEntry |
Filters the given iterable of JarEntry instances using the specified JarEntryFilter. |
extract |
Extracts the contents of the specified JAR file to the given target directory. |
extract |
Extracts the contents of the specified JAR file to the given target directory, optionally filtering entries. |
extract |
Extracts entries from a JAR file to the specified target directory, optionally filtering which entries to extract. |
extract |
Extracts entries from a JAR resource pointed by the given URL to the specified target directory, |
isDirectoryEntry |
Determines whether the specified URL points to a directory entry within a JAR file. |
public static JarFile toJarFile(URL jarURL)The resource path of Manifest file in JAR archive.
Typically located under META-INF/MANIFEST.MF in standard Java archives.
/
public static final String MANIFEST_RESOURCE_PATH = "META-INF/MANIFEST.MF";
/**
Creates a JarFile from the specified URL.
This method resolves the absolute path of the JAR file from the provided URL and constructs
a new JarFile instance. If the URL does not point to a valid JAR or file resource,
this method returns null.
`URL jarURL = new URL("jar:file:/path/to/file.jar!/entry");
JarFile jarFile = JarUtils.toJarFile(jarURL);
`
public static String resolveRelativePath(URL jarURL)Assert jarURL argument is valid , only supported protocols : ProtocolConstants#JAR_PROTOCOL jar and
ProtocolConstants#FILE_PROTOCOL file
public static String resolveJarAbsolutePath(URL jarURL)Resolves the absolute path of the JAR file from the provided URL.
This method ensures that the URL protocol is either "jar" or "file", and then resolves
the absolute path to the corresponding JAR archive on the file system. If the URL does not
point to a valid JAR or file resource, this method returns null.
`URL jarURL = new URL("jar:file:/path/to/file.jar!/com/example/resource.txt");
String absolutePath = JarUtils.resolveJarAbsolutePath(jarURL);
System.out.println(absolutePath); // Output: /path/to/file.jar
`
public static List<JarEntry> filter(JarFile jarFile, JarEntryFilter jarEntryFilter)Filters the entries of a JAR file based on the provided JarEntryFilter.
This method iterates through all entries in the given JAR file and applies the filter to selectively include
or exclude entries. If the provided JarFile is null or empty, an empty list is returned.
`JarFile jarFile = new JarFile("example.jar");
JarEntryFilter classFileFilter = entry -> entry.getName().endsWith(".class");
List filteredEntries = JarUtils.filter(jarFile, classFileFilter);
`
public static JarEntry findJarEntry(URL jarURL)Filters the given iterable of JarEntry instances using the specified JarEntryFilter.
`List entries = // ... obtain jar entries
JarEntryFilter filter = entry -> entry.getName().endsWith(".xml");
List filtered = JarUtils.doFilter(entries, filter);
`
Since: 1.0.0
public static void extract(File jarSourceFile, File targetDirectory)Extracts the contents of the specified JAR file to the given target directory.
This method extracts all entries from the provided JAR file into the target directory, preserving the original directory structure. If the JAR file contains nested directories, they will be recreated under the target directory.
`File jarFile = new File("example.jar");
File outputDir = new File("/path/to/output");
JarUtils.extract(jarFile, outputDir);
`
public static void extract(File jarSourceFile, File targetDirectory, JarEntryFilter jarEntryFilter)Extracts the contents of the specified JAR file to the given target directory, optionally filtering entries.
This method extracts entries from the provided JAR file into the target directory. If a filter is provided, only entries accepted by the filter will be extracted. The original directory structure of the JAR is preserved under the target directory.
`File jarFile = new File("example.jar");
File outputDir = new File("/path/to/output");
// Extract all entries
JarUtils.extract(jarFile, outputDir, null);
// Extract only .class files
JarEntryFilter classFileFilter = entry -> entry.getName().endsWith(".class");
JarUtils.extract(jarFile, outputDir, classFileFilter);
`
public static void extract(JarFile jarFile, File targetDirectory, JarEntryFilter jarEntryFilter)Extracts entries from a JAR file to the specified target directory, optionally filtering which entries to extract.
This method filters the entries in the JAR file using the provided JarEntryFilter, and extracts only those
entries that are accepted by the filter. If no filter is provided (i.e., null), all entries will be extracted.
The directory structure within the JAR is preserved under the target directory.
`JarFile jarFile = new JarFile("example.jar");
File outputDir = new File("/path/to/output");
// Extract all entries
JarUtils.extract(jarFile, outputDir, null);
// Extract only .class files
JarEntryFilter classFileFilter = entry -> entry.getName().endsWith(".class");
JarUtils.extract(jarFile, outputDir, classFileFilter);
`
public static void extract(URL jarResourceURL, File targetDirectory, JarEntryFilter jarEntryFilter)Extracts entries from a JAR resource pointed by the given URL to the specified target directory, optionally filtering which entries to extract.
This method resolves the JAR file and relative path from the provided URL, filters the entries
using the given JarEntryFilter, and extracts them to the target directory while preserving
the original directory structure. If no filter is provided (i.e., null), all entries under
the resolved path will be extracted.
`URL jarURL = new URL("jar:file:/path/to/file.jar!/com/example/");
File outputDir = new File("/path/to/output");
// Extract all entries under 'com/example/'
JarUtils.extract(jarURL, outputDir, null);
// Extract only .class files under 'com/example/'
JarEntryFilter classFileFilter = entry -> entry.getName().endsWith(".class");
JarUtils.extract(jarURL, outputDir, classFileFilter);
`
public static boolean isDirectoryEntry(URL url)Determines whether the specified URL points to a directory entry within a JAR file.
This method checks if the given URL represents a directory entry in a JAR archive. It supports only the "jar" protocol. For URLs with the "jar" protocol, it resolves the JAR file and verifies if the relative path corresponds to a directory entry. If the relative path is empty, it is treated as the root directory of the JAR.
`URL jarURL = new URL("jar:file:/path/to/file.jar!/");
boolean isDirectory = JarUtils.isDirectoryEntry(jarURL);
System.out.println(isDirectory); // Output: true
URL fileURL = new URL("jar:file:/path/to/file.jar!/com/example/");
isDirectory = JarUtils.isDirectoryEntry(fileURL);
System.out.println(isDirectory); // Output: true
URL resourceURL = new URL("jar:file:/path/to/file.jar!/com/example/resource.txt");
isDirectory = JarUtils.isDirectoryEntry(resourceURL);
System.out.println(isDirectory); // Output: false
`
JarEntryJarFile
This documentation was auto-generated from the source code of microsphere-java.
annotation-processor
- ConfigurationPropertyAnnotationProcessor
- ConfigurationPropertyJSONElementVisitor
- FilerProcessor
- ResourceProcessor
java-annotations
java-core
- ACLLoggerFactory
- AbstractArtifactResourceResolver
- AbstractConverter
- AbstractDeque
- AbstractEventDispatcher
- AbstractLogger
- AbstractURLClassPathHandle
- AccessibleObjectUtils
- AdditionalMetadataResourceConfigurationPropertyLoader
- AnnotationUtils
- ArchiveFileArtifactResourceResolver
- ArrayEnumeration
- ArrayStack
- ArrayUtils
- Artifact
- ArtifactDetector
- ArtifactResourceResolver
- Assert
- BannedArtifactClassLoadingExecutor
- BaseUtils
- BeanMetadata
- BeanProperty
- BeanUtils
- ByteArrayToObjectConverter
- CharSequenceComparator
- CharSequenceUtils
- CharsetUtils
- ClassDataRepository
- ClassDefinition
- ClassFileJarEntryFilter
- ClassFilter
- ClassLoaderUtils
- ClassPathResourceConfigurationPropertyLoader
- ClassPathUtils
- ClassUtils
- ClassicProcessIdResolver
- ClassicURLClassPathHandle
- CollectionUtils
- Compatible
- CompositeSubProtocolURLConnectionFactory
- CompositeURLStreamHandlerFactory
- ConditionalEventListener
- ConfigurationProperty
- ConfigurationPropertyGenerator
- ConfigurationPropertyLoader
- ConfigurationPropertyReader
- Configurer
- ConsoleURLConnection
- Constants
- ConstructorDefinition
- ConstructorUtils
- Converter
- Converters
- CustomizedThreadFactory
- DefaultConfigurationPropertyGenerator
- DefaultConfigurationPropertyReader
- DefaultDeserializer
- DefaultEntry
- DefaultSerializer
- DelegatingBlockingQueue
- DelegatingDeque
- DelegatingIterator
- DelegatingQueue
- DelegatingScheduledExecutorService
- DelegatingURLConnection
- DelegatingURLStreamHandlerFactory
- DelegatingWrapper
- Deprecation
- Deserializer
- Deserializers
- DirectEventDispatcher
- DirectoryFileFilter
- EmptyDeque
- EmptyIterable
- EmptyIterator
- EnumerationIteratorAdapter
- EnumerationUtils
- Event
- EventDispatcher
- EventListener
- ExceptionUtils
- ExecutableDefinition
- ExecutableUtils
- ExecutorUtils
- ExtendableProtocolURLStreamHandler
- FastByteArrayInputStream
- FastByteArrayOutputStream
- FieldDefinition
- FieldUtils
- FileChangedEvent
- FileChangedListener
- FileConstants
- FileExtensionFilter
- FileUtils
- FileWatchService
- Filter
- FilterOperator
- FilterUtils
- FormatUtils
- Functional
- GenericEvent
- GenericEventListener
- Handler
- Handler
- HierarchicalClassComparator
- IOFileFilter
- IOUtils
- ImmutableEntry
- IterableAdapter
- IterableUtils
- Iterators
- JDKLoggerFactory
- JSON
- JSONArray
- JSONException
- JSONObject
- JSONStringer
- JSONTokener
- JSONUtils
- JarEntryFilter
- JarUtils
- JavaType
- JmxUtils
- ListUtils
- Listenable
- Lists
- Logger
- LoggerFactory
- LoggingFileChangedListener
- MBeanAttribute
- MBeanAttributeInfoBuilder
- MBeanConstructorInfoBuilder
- MBeanDescribableBuilder
- MBeanExecutableInfoBuilder
- MBeanFeatureInfoBuilder
- MBeanInfoBuilder
- MBeanNotificationInfoBuilder
- MBeanOperationInfoBuilder
- MBeanParameterInfoBuilder
- ManagementUtils
- ManifestArtifactResourceResolver
- MapToPropertiesConverter
- MapUtils
- Maps
- MavenArtifact
- MavenArtifactResourceResolver
- MemberDefinition
- MemberUtils
- MetadataResourceConfigurationPropertyLoader
- MethodDefinition
- MethodHandleUtils
- MethodHandlesLookupUtils
- MethodUtils
- ModernProcessIdResolver
- ModernURLClassPathHandle
- Modifier
- MultiValueConverter
- MultipleType
- MutableInteger
- MutableURLStreamHandlerFactory
- NameFileFilter
- NoOpLogger
- NoOpLoggerFactory
- NoOpURLClassPathHandle
- NumberToByteConverter
- NumberToCharacterConverter
- NumberToDoubleConverter
- NumberToFloatConverter
- NumberToIntegerConverter
- NumberToLongConverter
- NumberToShortConverter
- NumberUtils
- ObjectToBooleanConverter
- ObjectToByteArrayConverter
- ObjectToByteConverter
- ObjectToCharacterConverter
- ObjectToDoubleConverter
- ObjectToFloatConverter
- ObjectToIntegerConverter
- ObjectToLongConverter
- ObjectToOptionalConverter
- ObjectToShortConverter
- ObjectToStringConverter
- PackageNameClassFilter
- PackageNameClassNameFilter
- ParallelEventDispatcher
- ParameterizedTypeImpl
- PathConstants
- Predicates
- Prioritized
- PriorityComparator
- ProcessExecutor
- ProcessIdResolver
- ProcessManager
- PropertiesToStringConverter
- PropertiesUtils
- PropertyConstants
- PropertyResourceBundleControl
- PropertyResourceBundleUtils
- ProtocolConstants
- ProxyUtils
- QueueUtils
- ReadOnlyIterator
- ReflectionUtils
- ReflectiveConfigurationPropertyGenerator
- ReflectiveDefinition
- ResourceConstants
- ReversedDeque
- Scanner
- SecurityUtils
- SeparatorConstants
- Serializer
- Serializers
- ServiceLoaderURLStreamHandlerFactory
- ServiceLoaderUtils
- ServiceLoadingURLClassPathHandle
- SetUtils
- Sets
- Sfl4jLoggerFactory
- ShutdownHookCallbacksThread
- ShutdownHookUtils
- SimpleClassScanner
- SimpleFileScanner
- SimpleJarEntryScanner
- SingletonDeque
- SingletonEnumeration
- SingletonIterator
- StackTraceUtils
- StandardFileWatchService
- StandardURLStreamHandlerFactory
- StopWatch
- StreamArtifactResourceResolver
- Streams
- StringBuilderWriter
- StringConverter
- StringDeserializer
- StringSerializer
- StringToArrayConverter
- StringToBlockingDequeConverter
- StringToBlockingQueueConverter
- StringToBooleanConverter
- StringToByteConverter
- StringToCharArrayConverter
- StringToCharacterConverter
- StringToClassConverter
- StringToCollectionConverter
- StringToDequeConverter
- StringToDoubleConverter
- StringToDurationConverter
- StringToFloatConverter
- StringToInputStreamConverter
- StringToIntegerConverter
- StringToIterableConverter
- StringToListConverter
- StringToLongConverter
- StringToMultiValueConverter
- StringToNavigableSetConverter
- StringToQueueConverter
- StringToSetConverter
- StringToShortConverter
- StringToSortedSetConverter
- StringToStringConverter
- StringToTransferQueueConverter
- StringUtils
- SubProtocolURLConnectionFactory
- SymbolConstants
- SystemUtils
- ThrowableAction
- ThrowableBiConsumer
- ThrowableBiFunction
- ThrowableConsumer
- ThrowableFunction
- ThrowableSupplier
- ThrowableUtils
- TrueClassFilter
- TrueFileFilter
- TypeArgument
- TypeFinder
- TypeUtils
- URLClassPathHandle
- URLUtils
- UnmodifiableDeque
- UnmodifiableIterator
- UnmodifiableQueue
- Utils
- ValueHolder
- Version
- VersionUtils
- VirtualMachineProcessIdResolver
- Wrapper
- WrapperProcessor
java-test
- AbstractAnnotationProcessingTest
- Ancestor
- AnnotationProcessingTestProcessor
- ArrayTypeModel
- CollectionTypeModel
- Color
- CompilerInvocationInterceptor
- ConfigurationPropertyModel
- DefaultTestService
- GenericTestService
- MapTypeModel
- Model
- Parent
- PrimitiveTypeModel
- SimpleTypeModel
- StringArrayList
- TestAnnotation
- TestService
- TestServiceImpl
jdk-tools
lang-model