Verified Owner
Top Description Fields Constructors Methods
org.jabref.logic.util.io

public Class FileUtil

extends Object
Class Inheritance
Imports
java.io.File, .IOException, .UncheckedIOException, java.net.URI, .URISyntaxException, java.nio.file.FileSystems, .Files, .InvalidPathException, .Path, .StandardCopyOption, java.util.ArrayDeque, .ArrayList, .Arrays, .Collections, .Comparator, .Deque, .List, .Optional, java.util.regex.Pattern, java.util.stream.Stream, org.jabref.logic.FilePreferences, org.jabref.logic.citationkeypattern.BracketedPattern, org.jabref.logic.layout.format.RemoveLatexCommandsFormatter, org.jabref.logic.os.OS, org.jabref.logic.util.StandardFileType, org.jabref.logic.util.strings.StringUtil, org.jabref.model.database.BibDatabase, .BibDatabaseContext, org.jabref.model.entry.BibEntry, .LinkedFile, org.jabref.model.entry.field.StandardField, mslinks.ShellLink, .ShellLinkException, org.apache.commons.io.FileUtils, .FilenameUtils, org.jspecify.annotations.NonNull, org.slf4j.Logger, .LoggerFactory

The idea of this class is to add general functionality that could possibly even in the Java NIO package, such as getting/adding file extension etc.

Field Summary

Modifier and TypeField and Description
private static final String
private static final String
private static final int
private static final int[]
ILLEGAL_CHARS

MUST ALWAYS BE A SORTED ARRAY because it is used in a binary search

public static final boolean
private static final Logger
public static final int
private static final String
private static final RemoveLatexCommandsFormatter
private static final Pattern

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static Path

Returns:

the modified file name
addExtension
(Path
the path to add the extension to
path
,
String
the extension to add
extension
)

Adds an extension to the given file name.

private static Path

Returns:

a windows-style path
buildWindowsPathWithDriveLetterIndex
(String
the input file path
path
,
int
the index driver letter, zero-based indexing
letterIndex
)

Builds a Windows-style path from a Cygwin-style path using a known prefix index.

public static Path

Returns:

the converted path if running on Windows and path is in Cygwin format; otherwise, returns the original path
convertCygwinPathToWindows
(String
the input file path
filePath
)

Converts a Cygwin-style file path to a Windows-style path if the operating system is Windows.

public static boolean

Returns:

boolean Whether the copy succeeded or was stopped due to the file already existing.
copyFile
(Path
Path Source file
pathToSourceFile
,
Path
Path Destination file
pathToDestinationFile
,
boolean
boolean Determines whether the copy goes on even if the file exists.
replaceExisting
)

Copies a file.

public static String

Returns:

a suggested dirName
createDirNameFromPattern
(BibDatabase
the database, where the entry is located
database
,
BibEntry
the entry to which the directory should be linked to
entry
,
String
the dirname pattern
directoryNamePattern
)

Determines directory name provided by an entry in a database

public static Optional<String>

Returns:

a suggested fileName
createFileNameFromPattern
(BibDatabase
the database, where the entry is located
database
,
BibEntry
the entry to which the file should be linked to
entry
,
String
the filename pattern
fileNamePattern
)

Determines filename provided by an entry in a database

public static boolean

Returns:

Boolean whether there is an illegal name.
detectBadFileName
(String
the fileName to detect
fileName
)

Detect illegal characters in given filename.

public static Optional<Path>
find(@NonNull BibDatabaseContext databaseContext, @NonNull String fileName, @NonNull FilePreferences filePreferences)

public static Optional<Path>
find(@NonNull String fileName, @NonNull List<@NonNull Path> directories)

Converts a relative filename to an absolute one, if necessary.

public static Optional<Path>

Returns:

an empty optional if the file does not exist, otherwise, the absolute path
find
(@NonNull String
the filename (e.g., a .pdf file), may contain path separators
fileName
,
@NonNull Path
the directory which should be search starting point
directory
)

Converts a relative filename to an absolute one, if necessary.

public static List<Path>

Returns:

a list including all found paths to files that match the defined conditions
findListOfFiles
(String
the name of the file that should be found
filename
,
List<Path>
the directories that will be searched
directories
)

Finds a file inside a list of directory structures.

public static Optional<Path>

Returns:

the path to the first file that matches the defined conditions
findSingleFileRecursively
(String
the name of the file that should be found
filename
,
Path
the rootDirectory that will be searched
rootDirectory
)

Finds a file inside a directory structure.

public static String
getBaseName(String fileName)

Returns the name part of a file name.

public static String
getBaseName(Path fileNameWithExtension)

Returns: the name part of a file name (i.e., everything before last ".")

public static Optional<String>

Returns:

the extension (without leading dot), trimmed and in lowercase.
getFileExtension
(@NonNull String fileName)

Returns the extension of a file name or Optional.empty() if the file does not have one (no "." in name).

public static Optional<String>

Returns:

the extension (without leading dot), trimmed and in lowercase
getFileExtension
(@NonNull Path file)

Returns the extension of a file or Optional.empty() if the file does not have one (no "." in name).

public static Optional<String>

Returns:

the extracted filename, or Optional.empty if there is none.
getFileNameFromUrl
(@NonNull String
the URL string to extract the filename from
link
)

Extracts the filename from a URL, which is found between the last slash '/' and first query '?'.

public static Optional<String>
getFileSize(@NonNull Path path)

Returns the human-readable size of a file, or an empty optional if it cannot be determined.

public static Path
getInitialDirectory(BibDatabaseContext databaseContext, Path workingDirectory)

Returns: Path of current panel database directory or the standard working directory in case the database was not saved yet

public static List<Path>

Returns:

list of files. May be empty
getListOfLinkedFiles
(@NonNull List<BibEntry>
list of BibTeX entries
entries
,
@NonNull List<Path>
list of directories to try for expansion
fileDirs
)

Returns the list of linked files.

public static Optional<String>

Returns:

Optional.empty() if the paths are disjoint
getUniquePathDirectory
(List<String>
List of paths as Strings
paths
,
Path
The to be tested path
comparePath
)

Looks for the shortest unique path of the parent directory in the list of paths

public static Optional<String>

Returns:

Shortest unique path fragment (if exists) - Optional.empty() if the paths are disjoint
getUniquePathFragment
(List<String>
List of paths as Strings
paths
,
Path
The to be shortened path
comparePath
)

Looks for the shortest unique path in the list of paths

public static String
getValidFileName(String fileName)

Returns a valid filename for most operating systems.

public static boolean

Returns:

True if file extension is ".bib", false otherwise
isBibFile
(Path
The file to check
file
)

Test if the file is a bib file by simply checking the extension to be ".bib" (case-insensitive)

public static boolean
isCharLegal(char c)

public static boolean

Returns:

true if file extension is an image, false otherwise
isImage
(Path
The file to check
file
)

Test if the file is an image file by simply checking if its extension is an image extension

public static boolean

Returns:

True if file extension is ".pdf", false otherwise
isPDFFile
(Path
The file to check
file
)

Test if the file is a pdf file by simply checking the extension to be ".pdf" (case-insensitive)

public static boolean

Returns:

true if file extension is .lnk, false otherwise
isShortcutFile
(Path
The file to check
file
)

Test if the file is a shortcut file by checking the extension to be ".lnk" (case-insensitive)

public static Path
relativize(Path
the file to be shortened
file
,
List<Path>
directories to check
directories
)

Converts an absolute file to a relative one, if possible.

public static Path
relativize(Path
the file path to be shortened
path
,
BibDatabaseContext databaseContext, FilePreferences filePreferences)

Converts an absolute file to a relative one, if possible.

public static List<BibEntry>
relativize(List<BibEntry> entries, BibDatabaseContext databaseContext, FilePreferences filePreferences)

Relativizes all BibEntries given to (!) the given database context

⚠ Modifies the entries in the list ⚠

public static Path

Returns:

The resolved path if file is a .lnk on Windows and the target is a valid file, otherwise returns the original path
resolveIfShortcut
(Path
The path to check (may be .lnk or any other file)
path
)

Resolves a Windows shortcut (.lnk) file to its target path.

public static String

Returns:

the original fileName if fileName.length() <= maxLength. Otherwise, a shortened fileName
shortenFileName
(String
the given file name to be shortened
fileName
,
Integer
the maximum number of characters in the string after shortening (including the extension)
maxLength
)

Shorten a given file name in the middle of the name using ellipsis.

public static String
toPortableString(Path path)

Creates a string representation of the given path that should work on all systems.

private static Optional<Path>
public static List<String>

Returns:

the minimal unique path substring for each file path
uniquePathSubstrings
(List<String>
the file paths
paths
)

Creates the minimal unique path substring for each file among multiple file paths.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

CYGDRIVE_PREFIXback to summary
private static final String CYGDRIVE_PREFIX
ELLIPSISback to summary
private static final String ELLIPSIS
ELLIPSIS_LENGTHback to summary
private static final int ELLIPSIS_LENGTH
ILLEGAL_CHARSback to summary
private static final int[] ILLEGAL_CHARS

MUST ALWAYS BE A SORTED ARRAY because it is used in a binary search

IS_POSIX_COMPLIANTback to summary
public static final boolean IS_POSIX_COMPLIANT
LOGGERback to summary
private static final Logger LOGGER
MAXIMUM_FILE_NAME_LENGTHback to summary
public static final int MAXIMUM_FILE_NAME_LENGTH
MNT_PREFIXback to summary
private static final String MNT_PREFIX
REMOVE_LATEX_COMMANDS_FORMATTERback to summary
private static final RemoveLatexCommandsFormatter REMOVE_LATEX_COMMANDS_FORMATTER
ROOT_DRIVE_PATTERNback to summary
private static final Pattern ROOT_DRIVE_PATTERN

Constructor Detail

FileUtilback to summary
private FileUtil()

Method Detail

addExtensionback to summary
public static Path addExtension(Path path, String extension)

Adds an extension to the given file name. The original extension is not replaced. That means, "demo.bib", ".sav" gets "demo.bib.sav" and not "demo.sav"

Warning

If "ext" is passed, this is literally added. Thus addExtension("tmp.txt", "ext") leads to "tmp.txtext".

Parameters
path:Path

the path to add the extension to

extension:String

the extension to add

Returns:Path

the modified file name

buildWindowsPathWithDriveLetterIndexback to summary
private static Path buildWindowsPathWithDriveLetterIndex(String path, int letterIndex)

Builds a Windows-style path from a Cygwin-style path using a known prefix index.

Parameters
path:String

the input file path

letterIndex:int

the index driver letter, zero-based indexing

Returns:Path

a windows-style path

convertCygwinPathToWindowsback to summary
public static Path convertCygwinPathToWindows(String filePath)

Converts a Cygwin-style file path to a Windows-style path if the operating system is Windows.

Supported formats:

  • /cygdrive/c/Users/... → C:\Users...
  • /mnt/c/Users/... → C:\Users...
  • /c/Users/... → C:\Users...
Parameters
filePath:String

the input file path

Returns:Path

the converted path if running on Windows and path is in Cygwin format; otherwise, returns the original path

copyFileback to summary
public static boolean copyFile(Path pathToSourceFile, Path pathToDestinationFile, boolean replaceExisting)

Copies a file.

Parameters
pathToSourceFile:Path

Path Source file

pathToDestinationFile:Path

Path Destination file

replaceExisting:boolean

boolean Determines whether the copy goes on even if the file exists.

Returns:boolean

boolean Whether the copy succeeded or was stopped due to the file already existing.

createDirNameFromPatternback to summary
public static String createDirNameFromPattern(BibDatabase database, BibEntry entry, String directoryNamePattern)

Determines directory name provided by an entry in a database

Parameters
database:BibDatabase

the database, where the entry is located

entry:BibEntry

the entry to which the directory should be linked to

directoryNamePattern:String

the dirname pattern

Returns:String

a suggested dirName

createFileNameFromPatternback to summary
public static Optional<String> createFileNameFromPattern(BibDatabase database, BibEntry entry, String fileNamePattern)

Determines filename provided by an entry in a database

Parameters
database:BibDatabase

the database, where the entry is located

entry:BibEntry

the entry to which the file should be linked to

fileNamePattern:String

the filename pattern

Returns:Optional<String>

a suggested fileName

detectBadFileNameback to summary
public static boolean detectBadFileName(String fileName)

Detect illegal characters in given filename.

Parameters
fileName:String

the fileName to detect

Returns:boolean

Boolean whether there is an illegal name.

See Also
org.jabref.logic.util.io.FileNameCleaner#cleanFileName
findback to summary
public static Optional<Path> find(@NonNull BibDatabaseContext databaseContext, @NonNull String fileName, @NonNull FilePreferences filePreferences)
findback to summary
public static Optional<Path> find(@NonNull String fileName, @NonNull List<@NonNull Path> directories)

Converts a relative filename to an absolute one, if necessary. Returns an empty optional if the file does not exist.

Will look in each of the given directories starting from the beginning and returning the first found file to match if any.

findback to summary
public static Optional<Path> find(@NonNull String fileName, @NonNull Path directory)

Converts a relative filename to an absolute one, if necessary.

Parameters
fileName:@NonNull String

the filename (e.g., a .pdf file), may contain path separators

directory:@NonNull Path

the directory which should be search starting point

Returns:Optional<Path>

an empty optional if the file does not exist, otherwise, the absolute path

findListOfFilesback to summary
public static List<Path> findListOfFiles(String filename, List<Path> directories)

Finds a file inside a list of directory structures. Will also look for the file inside nested directories.

Parameters
filename:String

the name of the file that should be found

directories:List<Path>

the directories that will be searched

Returns:List<Path>

a list including all found paths to files that match the defined conditions

findSingleFileRecursivelyback to summary
public static Optional<Path> findSingleFileRecursively(String filename, Path rootDirectory)

Finds a file inside a directory structure. Will also look for the file inside nested directories.

Parameters
filename:String

the name of the file that should be found

rootDirectory:Path

the rootDirectory that will be searched

Returns:Optional<Path>

the path to the first file that matches the defined conditions

getBaseNameback to summary
public static String getBaseName(String fileName)

Returns the name part of a file name.

Typically, this is everything before last ".". Exception: if only a single dot is contained and nothing is before the last dot - all is returned

getBaseNameback to summary
public static String getBaseName(Path fileNameWithExtension)
Returns:String

the name part of a file name (i.e., everything before last ".")

getFileExtensionback to summary
public static Optional<String> getFileExtension(@NonNull String fileName)

Returns the extension of a file name or Optional.empty() if the file does not have one (no "." in name).

In case the filename starts with a "." and only has one ".", the part after the dot is NOT the extension

Returns:Optional<String>

the extension (without leading dot), trimmed and in lowercase.

getFileExtensionback to summary
public static Optional<String> getFileExtension(@NonNull Path file)

Returns the extension of a file or Optional.empty() if the file does not have one (no "." in name).

Returns:Optional<String>

the extension (without leading dot), trimmed and in lowercase

getFileNameFromUrlback to summary
public static Optional<String> getFileNameFromUrl(@NonNull String link)

Extracts the filename from a URL, which is found between the last slash '/' and first query '?'. Does not check that the file is a valid URL.

Parameters
link:@NonNull String

the URL string to extract the filename from

Returns:Optional<String>

the extracted filename, or Optional.empty if there is none.

getFileSizeback to summary
public static Optional<String> getFileSize(@NonNull Path path)

Returns the human-readable size of a file, or an empty optional if it cannot be determined.

getInitialDirectoryback to summary
public static Path getInitialDirectory(BibDatabaseContext databaseContext, Path workingDirectory)
Returns:Path

Path of current panel database directory or the standard working directory in case the database was not saved yet

getListOfLinkedFilesback to summary
public static List<Path> getListOfLinkedFiles(@NonNull List<BibEntry> entries, @NonNull List<Path> fileDirs)

Returns the list of linked files. The files have the absolute filename

Parameters
entries:@NonNull List<BibEntry>

list of BibTeX entries

fileDirs:@NonNull List<Path>

list of directories to try for expansion

Returns:List<Path>

list of files. May be empty

getUniquePathDirectoryback to summary
public static Optional<String> getUniquePathDirectory(List<String> paths, Path comparePath)

Looks for the shortest unique path of the parent directory in the list of paths

Parameters
paths:List<String>

List of paths as Strings

comparePath:Path

The to be tested path

Returns:Optional<String>

Optional.empty() if the paths are disjoint

getUniquePathFragmentback to summary
public static Optional<String> getUniquePathFragment(List<String> paths, Path comparePath)

Looks for the shortest unique path in the list of paths

Parameters
paths:List<String>

List of paths as Strings

comparePath:Path

The to be shortened path

Returns:Optional<String>

Shortest unique path fragment (if exists) - Optional.empty() if the paths are disjoint

getValidFileNameback to summary
public static String getValidFileName(String fileName)

Returns a valid filename for most operating systems.

It uses FileNameCleaner#cleanFileName(String) to remove illegal characters and then truncates the length to 255 chars, see MAXIMUM_FILE_NAME_LENGTH.

For "real" cleaning, FileNameCleaner#cleanFileName(String) should be used.

isBibFileback to summary
public static boolean isBibFile(Path file)

Test if the file is a bib file by simply checking the extension to be ".bib" (case-insensitive)

Parameters
file:Path

The file to check

Returns:boolean

True if file extension is ".bib", false otherwise

isCharLegalback to summary
public static boolean isCharLegal(char c)
isImageback to summary
public static boolean isImage(Path file)

Test if the file is an image file by simply checking if its extension is an image extension

Parameters
file:Path

The file to check

Returns:boolean

true if file extension is an image, false otherwise

isPDFFileback to summary
public static boolean isPDFFile(Path file)

Test if the file is a pdf file by simply checking the extension to be ".pdf" (case-insensitive)

Parameters
file:Path

The file to check

Returns:boolean

True if file extension is ".pdf", false otherwise

isShortcutFileback to summary
public static boolean isShortcutFile(Path file)

Test if the file is a shortcut file by checking the extension to be ".lnk" (case-insensitive)

Parameters
file:Path

The file to check

Returns:boolean

true if file extension is .lnk, false otherwise

relativizeback to summary
public static Path relativize(Path file, List<Path> directories)

Converts an absolute file to a relative one, if possible. Returns the parameter file itself if no shortening is possible.

This method works correctly only if directories are sorted decent in their length i.e. /home/user/literature/important before /home/user/literature.

Parameters
file:Path

the file to be shortened

directories:List<Path>

directories to check

relativizeback to summary
public static Path relativize(Path path, BibDatabaseContext databaseContext, FilePreferences filePreferences)

Converts an absolute file to a relative one, if possible. Returns the parameter file itself if no shortening is possible.

Parameters
path:Path

the file path to be shortened

relativizeback to summary
public static List<BibEntry> relativize(List<BibEntry> entries, BibDatabaseContext databaseContext, FilePreferences filePreferences)

Relativizes all BibEntries given to (!) the given database context

⚠ Modifies the entries in the list ⚠

resolveIfShortcutback to summary
public static Path resolveIfShortcut(Path path)

Resolves a Windows shortcut (.lnk) file to its target path. Uses the mslinks library which is already a project dependency. Only works on Windows systems. On other systems or if resolution fails, returns the original path.

Parameters
path:Path

The path to check (may be .lnk or any other file)

Returns:Path

The resolved path if file is a .lnk on Windows and the target is a valid file, otherwise returns the original path

shortenFileNameback to summary
public static String shortenFileName(String fileName, Integer maxLength)

Shorten a given file name in the middle of the name using ellipsis. Example: verylongfilenameisthis.pdf with maxLength = 20 is shortened into verylo...isthis.pdf

Parameters
fileName:String

the given file name to be shortened

maxLength:Integer

the maximum number of characters in the string after shortening (including the extension)

Returns:String

the original fileName if fileName.length() <= maxLength. Otherwise, a shortened fileName

toPortableStringback to summary
public static String toPortableString(Path path)

Creates a string representation of the given path that should work on all systems. This method should be used when a path needs to be stored in the bib file or preferences.

toRealPathback to summary
private static Optional<Path> toRealPath(Path path)
uniquePathSubstringsback to summary
public static List<String> uniquePathSubstrings(List<String> paths)

Creates the minimal unique path substring for each file among multiple file paths.

Parameters
paths:List<String>

the file paths

Returns:List<String>

the minimal unique path substring for each file path