-
Notifications
You must be signed in to change notification settings - Fork 53
io microsphere io FileUtils
Type: Class | Module: microsphere-java-core | Package: io.microsphere.io | Since: 1.0.0
Source:
microsphere-java-core/src/main/java/io/microsphere/io/FileUtils.java
File Utility
public abstract class FileUtils implements UtilsAuthor: Mercy
-
Introduced in:
1.0.0 -
Current Project Version:
0.1.10-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 |
File dir = new File("/path/to/directory");
int deletedCount = cleanDirectory(dir);
System.out.println("Deleted " + deletedCount + " files/directories.");Add 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.io.FileUtils;| Method | Description |
|---|---|
resolveRelativePath |
An empty immutable File array. |
getFileExtension |
Gets the extension of a file name, if any. |
deleteDirectory |
Deletes a directory and returns the number of deleted files and directories. |
cleanDirectory |
Cleans a directory by deleting all files and sub-directories without deleting the directory itself. |
forceDelete |
Deletes a file or directory and all its contents recursively. |
forceDeleteOnExit |
Schedules a file or directory for deletion on JVM exit. |
deleteDirectoryOnExit |
Schedules a directory for deletion on JVM exit, including all its contents. |
listFiles |
Schedules all files and subdirectories within the given directory for deletion on JVM exit. |
isSymlink |
Determines if the provided File is a symbolic link. |
getCanonicalFile |
Returns the canonical form of the specified File. |
public static String getFileExtension(String fileName)Gets the extension of a file name, if any.
-
getFileExtension("file.txt")returns"txt" -
getFileExtension("file.tar.gz")returns"gz" -
getFileExtension(".hiddenfile")returnsnull(no extension) -
getFileExtension("file")returnsnull(no extension) -
getFileExtension("")returnsnull(blank string) -
getFileExtension(null)returnsnull
public static int deleteDirectory(File directory)Deletes a directory and returns the number of deleted files and directories.
If the directory does not exist, it is considered already deleted, and this method returns 0.
-
deleteDirectory(new File("/tmp/testDir"))deletes the directory and all its contents, returning the total count of deleted files and directories. -
deleteDirectory(new File("/nonexistent/dir"))returns0since the directory does not exist.
public static int cleanDirectory(File directory)Cleans a directory by deleting all files and sub-directories without deleting the directory itself.
This method recursively deletes all files and directories within the provided directory. If any file or sub-directory cannot be deleted, an IOException is thrown after attempting to delete as many as possible. 1
`File dir = new File("/path/to/directory");
int deletedCount = cleanDirectory(dir);
System.out.println("Deleted " + deletedCount + " files/directories.");
`
public static int forceDelete(File file)Deletes a file or directory and all its contents recursively.
If the provided file is a directory, this method deletes all sub-directories and files,
then deletes the directory itself. If it's a regular file, it deletes that single file.
-
forceDelete(new File("/tmp/file.txt"))deletes the file and returns1 -
forceDelete(new File("/tmp/testDir"))deletes the directory and all its contents, returning the total count of deleted files and directories. -
forceDelete(new File("/nonexistent/file"))throws aNoSuchFileException
public static void forceDeleteOnExit(File file)Schedules a file or directory for deletion on JVM exit.
If the provided file is a directory, this method schedules all sub-directories and files,
then schedules the directory itself. If it's a regular file, it schedules that single file.
-
forceDeleteOnExit(new File("/tmp/file.txt"))schedules the file for deletion on exit. -
forceDeleteOnExit(new File("/tmp/testDir"))schedules the directory and all its contents for deletion on exit.
public static void deleteDirectoryOnExit(File directory)Schedules a directory for deletion on JVM exit, including all its contents.
If the directory does not exist, this method does nothing. If it does exist, it schedules the directory for deletion and recursively schedules all files and subdirectories for deletion.
-
deleteDirectoryOnExit(new File("/tmp/testDir"))ensures that the directory and all its contents are deleted when the JVM exits. -
deleteDirectoryOnExit(new File("/nonexistent/dir"))does nothing since the directory does not exist.
public static File[] listFiles(File directory)Schedules all files and subdirectories within the given directory for deletion on JVM exit.
This method does not delete the directory itself, only its contents. If the directory is a symbolic link, its contents will not be processed.
-
cleanDirectoryOnExit(new File("/tmp/testDir"))ensures that all contents of the directory are deleted when the JVM exits, but the directory itself remains. -
cleanDirectoryOnExit(new File("/nonexistent/dir"))does nothing since the directory does not exist.
public static boolean isSymlink(File file)Determines if the provided File is a symbolic link.
-
isSymlink(new File("/path/to/symlink"))returnstrueif it's a symbolic link. -
isSymlink(new File("/path/to/regularfile"))returnsfalseas it's not a symbolic link. -
isSymlink(null)throws aNullPointerException.
public static File getCanonicalFile(File file)Returns the canonical form of the specified File.
This method wraps the call to File#getCanonicalFile() in a try-catch block to handle any
checked exceptions via the io.microsphere.lang.function.ThrowableSupplier utility.
-
getCanonicalFile(new File("relative/path"))returns the canonical file object. - If the file does not exist or I/O error occurs, it will propagate as an unchecked exception.
FileUtils
This documentation was auto-generated from the source code of microsphere-java.
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
jdk-tools
lang-model
- AnnotatedElementJSONElementVisitor
- AnnotationUtils
- ClassUtils
- ConstructorUtils
- ElementUtils
- ExecutableElementComparator
- FieldUtils
- JSONAnnotationValueVisitor
- JSONElementVisitor
- LoggerUtils
- MemberUtils
- MessagerUtils
- MethodUtils
- ResolvableAnnotationValueVisitor
- StringAnnotationValue
- TypeUtils
annotation-processor
- ConfigurationPropertyAnnotationProcessor
- ConfigurationPropertyJSONElementVisitor
- FilerProcessor
- ResourceProcessor
java-test
- AbstractAnnotationProcessingTest
- Ancestor
- AnnotationProcessingTestProcessor
- ArrayTypeModel
- CollectionTypeModel
- Color
- CompilerInvocationInterceptor
- ConfigurationPropertyModel
- DefaultTestService
- GenericTestService
- MapTypeModel
- Model
- Parent
- PrimitiveTypeModel
- SimpleTypeModel
- StringArrayList
- TestAnnotation
- TestService
- TestServiceImpl