- org.apache.commons.io.FilenameUtils Example
- 1. File Name Components
- 2. Path Normalization
- 3. File Equality
- 4. Concatenation
- 5. Separator Conversion
- 6. Directory Search
- 7. Download Java Source Code
- Saved searches
- Use saved searches to filter your results more quickly
- ditschedev/filename-utils
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Apache Commons IO – FilenameUtils
- Декларация класса
- Характеристики
- Пример класса FilenameUtils
- Выход
org.apache.commons.io.FilenameUtils Example
Apache Commons IO is a library of utilities to assist with developing IO functionality. org.apache.commons.io package has utility classes to perform common tasks. FilenameUtils is one of the classes. This class has static methods for filename and filepath manipulation. This class aims to help avoid those problems related with moving file names used in unix and Windows environments. This article shows usage of some methods defined in this class. The class is from Apache Commons IO 2.4. Note the commons-io-2.4.jar file is required in the classpath to compile and run the examples. This library can be downloaded from the Apache Commons website. The examples are tested on Windows operating system. The Apache Commons IO 2.4 API usage requires Java SE 6 or greater. Some examples in this article require Java SE 7.
1. File Name Components
- X:\ – is the prefix
- JCG\articles\org.apache.commons.io.FilenameUtils Example\ – is the path without the prefix
- X:\JCG\articles\org.apache.commons.io.FilenameUtils Example\ – is the full path with the prefix
- notes.txt – is the name
- notes – is the base name
- txt – is the extension
The following example shows how the components can be retrieved from a given filename using various methods of FilenameUtils class.
import org.apache.commons.io.FilenameUtils; public class FilenameUtilsExample1 < public static void main(String [] args) < filenameComponents_(); >private static void filenameComponents_() < String filename = "X:\\JCG\\articles\\org.apache.commons.io.FilenameUtils Example\\notes.txt"; System.out.println("*** File name components ***"); System.out.println("File name: " + filename); String prefix = FilenameUtils.getPrefix(filename); System.out.println("Prefix: " + prefix); String path = FilenameUtils.getPath(filename); System.out.println("Path: " + path); String fullPath = FilenameUtils.getFullPath(filename); System.out.println("Full path: " + fullPath); String name = FilenameUtils.getName(filename); System.out.println("Name: " + name); String baseName = FilenameUtils.getBaseName(filename); System.out.println("Base name: " + baseName); String extension = FilenameUtils.getExtension(filename); System.out.println("Extension: " + extension); >>
*** File name components *** File name: X:\JCG\articles\org.apache.commons.io.FilenameUtils Example\notes.txt Prefix: X:\ Path: JCG\articles\org.apache.commons.io.FilenameUtils Example\ Full path: X:\JCG\articles\org.apache.commons.io.FilenameUtils Example\ Name: notes.txt Base name: notes Extension: txt
2. Path Normalization
Normalizing a file path is removing double (..) and single (.) dot path steps. The normalize() method is used for this. This method works on Windows as well as unix systems.
The following example shows normalizing a path with single and double dots:
import org.apache.commons.io.FilenameUtils; public class FilenameUtilsExample1 < public static void main(String [] args) < normalize_(); >private static void normalize_() < System.out.println("*** Normalization ***"); String filename = "X:\\JCG\\.\\org.apache.commons.io.FilenameUtils Example\\notes.txt"; System.out.println("Before: " + filename); String normalized = FilenameUtils.normalize(filename); System.out.println("After single dot normalization: " + normalized); filename = "X:\\JCG\\articles\\..\\notes.txt"; System.out.println("Before: " + filename); normalized = FilenameUtils.normalize(filename); System.out.println("After double dot normalization: " + normalized); >>
*** Normalization *** Before: X:\JCG\.\org.apache.commons.io.FilenameUtils Example\notes.txt After single dot normalization: X:\JCG\org.apache.commons.io.FilenameUtils Example\notes.txt Before: X:\JCG\articles\..\notes.txt After double dot normalization: X:\JCG\notes.txt
From the output note that for the double dot (..) normalization, the double dot path segment and also the one segment before that are removed.
3. File Equality
The equals() method checks if two filename strings are same. This is a null safe method – the supplied filename can be a null and no exceptions are thrown.
A variation of this method is the equalsNormalized() . This method checks if two filename strings are same, after normalizing the filenames.
The following example shows the usage of the equals() method.
import org.apache.commons.io.FilenameUtils; public class FilenameUtilsExample1 < public static void main(String [] args) < equals_(); >private static void equals_() < System.out.println("*** File name equality ***"); String filename1 = "FilenameUtilsExample.java"; String filename2 = "FilenameUtilsExample.java"; System.out.println("Filename 1: " + filename1); System.out.println("Filename 2: " + filename2); boolean result = FilenameUtils.equals(filename1, filename2); System.out.println("Equals: " + result); filename1 = null; System.out.println("Filename 1: " + filename1); System.out.println("Filename 2: " + filename2); result = FilenameUtils.equals(filename1, filename2); System.out.println("Equals: " + result); >>
*** File name equality *** Filename 1: FilenameUtilsExample.java Filename 2: FilenameUtilsExample.java Equals: true Filename 1: null Filename 2: FilenameUtilsExample.java Equals: false
4. Concatenation
The concat() method concatenates a filename to a base path. For this method, the first argument is the base path, the second is the path to concatenate. The returned path is always normalized.
The following example shows the usage of the concat() method.
import org.apache.commons.io.FilenameUtils; public class FilenameUtilsExample1 < public static void main(String [] args) < concat_(); >private static void concat_() < System.out.println("*** Concatenation ***"); // base and added names are paths String filename1 = "X:\\JCG\\Examples\\org.apache.commons.io.FilenameUtils"; String filename2 = "articles\\"; String concatenatedPath = FilenameUtils.concat(filename1, filename2); System.out.println("Filename 1: " + filename1 ); System.out.println("Filename 2: " + filename2 ); System.out.println("Concatenated: " + concatenatedPath); // base is path and added name is file name filename1 = "X:\\JCG\\Examples\\org.apache.commons.io.FilenameUtils"; filename2 = "FilenameUtilsExample.java"; concatenatedPath = FilenameUtils.concat(filename1, filename2); System.out.println("Filename 1: " + filename1 ); System.out.println("Filename 2: " + filename2 ); System.out.println("Concatenated: " + concatenatedPath); // base is reative path and added name is file name filename1 = "org.apache.commons.io.FilenameUtils"; filename2 = "FilenameUtilsExample.java"; concatenatedPath = FilenameUtils.concat(filename1, filename2); System.out.println("Filename 1: " + filename1 ); System.out.println("Filename 2: " + filename2 ); System.out.println("Concatenated: " + concatenatedPath); >>
*** Concatenation *** Filename 1: X:\JCG\Examples\org.apache.commons.io.FilenameUtils Filename 2: articles\ Concatenated: X:\JCG\Examples\org.apache.commons.io.FilenameUtils\articles\ Filename 1: X:\JCG\Examples\org.apache.commons.io.FilenameUtils Filename 2: FilenameUtilsExample.java Concatenated: X:\JCG\Examples\org.apache.commons.io.FilenameUtils\FilenameUtilsExample.java Filename 1: org.apache.commons.io.FilenameUtils Filename 2: FilenameUtilsExample.java Concatenated: org.apache.commons.io.FilenameUtils\FilenameUtilsExample.java
5. Separator Conversion
This class defines methods to convert the path separator from unix (/) to Windows (\) and vice-versa.
The following example shows the usage of two methods separatorsToUnix() and separatorsToSystem() . There is also a method separatorsToWindows() to convert path separators to Windows system (\).
import org.apache.commons.io.FilenameUtils; public class FilenameUtilsExample1 < public static void main(String [] args) < separators_(); >private static void separators_() < System.out.println("*** Separator conversion ***"); String filename = "X:\\JCG\\articles\\org.apache.commons.io.FilenameUtils Example\\notes.txt"; System.out.println("File name: " + filename); filename = FilenameUtils.separatorsToUnix(filename); System.out.println("File name after separatorsToUnix(): " + filename); filename = "/JCG/articles/org.apache.commons.io.FilenameUtils Example/notes.txt"; System.out.println("File name: " + filename); filename = FilenameUtils.separatorsToSystem(filename); System.out.println("File name after separatorsToSystem(): " + filename); >>
*** Separator conversion *** File name: X:\JCG\articles\org.apache.commons.io.FilenameUtils Example\notes.txt File name after separatorsToUnix(): X:/JCG/articles/org.apache.commons.io.FilenameUtils Example/notes.txt File name: /JCG/articles/org.apache.commons.io.FilenameUtils Example/notes.txt File name after separatorsToSystem(): \JCG\articles\org.apache.commons.io.FilenameUtils Example\notes.txt
- File name: X:\JCG\articles\org.apache.commons.io.FilenameUtils Example\notes.txt
File name after separatorsToUnix(): X:/JCG/articles/org.apache.commons.io.FilenameUtils Example/notes.txt
The output shows the Windows path is converted to unix path. - File name: /JCG/articles/org.apache.commons.io.FilenameUtils Example/notes.txt
File name after separatorsToSystem(): \JCG\articles\org.apache.commons.io.FilenameUtils Example\notes.txt
The output shows the unix path is converted to Windows path; the program is run on a Windows system.
6. Directory Search
- extensions java or class using the isExtension() method; for example FileChannelRead.java
- matching wild card *Example?.txt; for example MyExample1.txt
The program iterates over a directory (note that a real directory with files is required) and uses the wild card and is extension methods for getting matched files. Note this example uses classes from java.nio.file package of Java SE 7 NIO2 File API.
import org.apache.commons.io.FilenameUtils; import java.io.IOException; import java.nio.file.Paths; import java.nio.file.Path; import java.nio.file.Files; import java.nio.file.DirectoryStream; public class FilenameUtilsExample2 < public static void main(String [] args) throws IOException < System.out.println("*** File extension and wildcard matching ***"); String [] extensions = ; String wildcardMatcher = "*Example?.txt"; Path dirPath = Paths.get("X:\\testdir\\"); System.out.println("Directory being searched: " + dirPath.toString()); DirectoryStream dirStream = Files.newDirectoryStream(dirPath); for (Path filePath : dirStream) < String filename = filePath.getFileName().toString(); System.out.println(filename); // file extension matching boolean fileFound = FilenameUtils.isExtension(filename, extensions); if (fileFound) < System.out.println(" file with java or class extension"); >// wild card matching fileFound = FilenameUtils.wildcardMatch(filename, wildcardMatcher); if (fileFound) < System.out.println(" file with *Example?.txt wild card match"); >> // end for loop dirStream.close(); > >
*** File extension and wildcard matching *** Directory being searched: X:\testdir archives commons-io-2.4.jar FileChannelRead.class file with java or class extension FileChannelRead.java file with java or class extension FilenameUtilsExample.java file with java or class extension FilenameUtilsExample1.txt file with *Example?.txt wild card match FilenameUtilsExample1a.txt FilenameUtilsExample2.txt file with *Example?.txt wild card match notes.txt readfile.txt screenshots.docx WatchEventExample.class file with java or class extension WatchEventExample.java file with java or class extension
- Directory being searched: X:\testdir – This is the path of the directory being searched.
- Note all files in the directory are listed. The files being searched are identified according to their matching. For example, FileChannelRead.class – file with java or class extension.
7. Download Java Source Code
This was an example of org.apache.commons.io.FilenameUtils
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A tiny yet powerfull collection of utils for processing filenames compareable to Apaches FilenameUtils for Java
ditschedev/filename-utils
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A tiny module written in TypeScript to help you with your filenames. A JavaScript version of the Apache FilenameUtils class.
To install the module, use your preferred package manager.
npm install filename-utils
First you need to import the functions you need from filename-utils .
import getExtension, getBaseName > from 'filename-utils';
After that you can use the functions as you’d like!.
getExtension(filename: string): string
Fetches the extension of a filename. Will return an empty string, if no filename can be resolved. Examples:
getExtension('image.png'); // returns => "png" getExtension('image.test.jpeg'); // returns => "jpeg" getExtension('shellscript'); // returns => "" getExtension('.htaccess'); // returns => ""
getBaseName(filename: string): string
Strips the extension off the filename and returns the base name.
getBaseName('image.png'); // returns => "image" getBaseName('image.test.jpeg'); // returns => "image.test" getBaseName('file'); // returns => "file" getBaseName('.env'); // returns => ""
About
A tiny yet powerfull collection of utils for processing filenames compareable to Apaches FilenameUtils for Java
Apache Commons IO – FilenameUtils
Предоставляет метод для работы с именами файлов без использования File Object. Он работает на разных операционных системах одинаково. Этот класс решает проблемы при переходе с машины для разработки на базе Windows на рабочую машину на основе Unix.
Декларация класса
Ниже приводится объявление для класса org.apache.commons.io.FilenameUtils.
public class FilenameUtils extends Object
Характеристики
Этот класс определяет шесть компонентов в имени файла. Рассмотрим пример расположения как C: \ dev \ project \ file.txt . Тогда компоненты –
- Префикс – C: \
- Относительный путь – dev \ project \
- Абсолютный путь – C: \ dev \ project \
- Имя – file.txt
- Базовое имя – файл
- Расширение – TXT
Чтобы определить каталог, добавьте разделитель к имени файла.
Пример класса FilenameUtils
import java.io.IOException; import org.apache.commons.io.FilenameUtils; public class IOTester public static void main(String[] args) try //Using FilenameUtils usingFilenameUtils(); > catch(IOException e) System.out.println(e.getMessage()); > > public static void usingFilenameUtils() throws IOException String path = "C:\\dev\\project\\file.txt"; System.out.println("Full Path: " +FilenameUtils.getFullPath(path)); System.out.println("Relative Path: " +FilenameUtils.getPath(path)); System.out.println("Prefix: " +FilenameUtils.getPrefix(path)); System.out.println("Extension: " + FilenameUtils.getExtension(path)); System.out.println("Base: " + FilenameUtils.getBaseName(path)); System.out.println("Name: " + FilenameUtils.getName(path)); String filename = "C:/commons/io/../lang/project.xml"; System.out.println("Normalized Path: " + FilenameUtils.normalize(filename)); > >
Выход
Будет напечатан следующий результат.