FileUtils
Utility class providing static helper methods for common file operations: name and extension parsing, temporary file and directory creation, file reading and writing, copying, MIME type detection, existence checks, and more. All methods are static.
Name and path utilities
Section titled “Name and path utilities”getFileName
Section titled “getFileName”Description:
| Method | Return values | Description |
|---|---|---|
| getFileName(String file) | String | Returns the file name without its extension. If no extension is present, returns the original name. |
- file: The file name (with or without path).
Example:
package com.openkm;
import com.openkm.util.FileUtils;import com.openkm.util.PathUtils;import java.io.File;
public class Test {
public static void main(String[] args) { try { File file = new File("/home/openkm/test.png"); String docName = PathUtils.getName(file.getPath()); String baseName = FileUtils.getFileName(docName); System.out.println(baseName); // "test" } catch (Exception e) { e.printStackTrace(); } }}getFileExtension
Section titled “getFileExtension”Description:
| Method | Return values | Description |
|---|---|---|
| getFileExtension(String file) | String | Returns the file extension without the leading dot. Returns an empty string if no extension is present. |
- file: The file name (with or without path).
Example:
package com.openkm;
import com.openkm.util.FileUtils;import com.openkm.util.PathUtils;import java.io.File;
public class Test {
public static void main(String[] args) { try { File file = new File("/home/openkm/test.png"); String docName = PathUtils.getName(file.getPath()); String extension = FileUtils.getFileExtension(docName); System.out.println(extension); // "png" } catch (Exception e) { e.printStackTrace(); } }}getParent
Section titled “getParent”Description:
| Method | Return values | Description |
|---|---|---|
| getParent(String file) | String | Returns the parent directory path of the given file path. Returns the root separator if there is no parent. |
Example:
String parent = FileUtils.getParent("/home/openkm/test.png");System.out.println(parent); // "/home/openkm"toValidFilename
Section titled “toValidFilename”Description:
| Method | Return values | Description |
|---|---|---|
| toValidFilename(String filename) | String | Removes characters that are reserved in Windows file names (\ / : " * ? < > |) from the given string. |
Example:
String safe = FileUtils.toValidFilename("report: Q1/2024.pdf");System.out.println(safe); // "report Q12024.pdf"getFileNameNotDuplicatedInDestinationPath
Section titled “getFileNameNotDuplicatedInDestinationPath”Description:
| Method | Return values | Description |
|---|---|---|
| getFileNameNotDuplicatedInDestinationPath(String pathFile, String name, String ext) | String | Returns a unique file name in the given directory. If <name>.<ext> already exists it appends a counter: <name>(1).<ext>, <name>(2).<ext>, etc. |
- pathFile: The target directory path.
- name: The desired file name without extension.
- ext: The file extension without leading dot.
Example:
String unique = FileUtils.getFileNameNotDuplicatedInDestinationPath("/home/openkm", "report", "pdf");System.out.println(unique); // "report.pdf" or "report(1).pdf" if already existsgenerateUniqueName
Section titled “generateUniqueName”Description:
| Method | Return values | Description |
|---|---|---|
| generateUniqueName(String basename) | String | Generates a unique file name by prepending the current timestamp (yyyyMMddHHmmss) to the given base name. |
Example:
String name = FileUtils.generateUniqueName("report.pdf");System.out.println(name); // e.g. "20240315143022report.pdf"Temporary file and directory creation
Section titled “Temporary file and directory creation”createTempDir
Section titled “createTempDir”Description:
| Method | Return values | Description |
|---|---|---|
| createTempDir() | File | Creates and returns a new unique temporary directory using the system temporary directory. |
Example:
File tmpDir = FileUtils.createTempDir();// use tmpDir ...FileUtils.deleteQuietly(tmpDir);createTempFile
Section titled “createTempFile”Description:
| Method | Return values | Description |
|---|---|---|
| createTempFile() | File | Creates and returns a new unique temporary file with the .tmp extension. |
createTempFile (with extension)
Section titled “createTempFile (with extension)”Description:
| Method | Return values | Description |
|---|---|---|
| createTempFile(String ext) | File | Creates and returns a new unique temporary file with the specified extension. |
- ext: The file extension without leading dot (e.g.
"pdf").
createSharedTempFile
Section titled “createSharedTempFile”Description:
| Method | Return values | Description |
|---|---|---|
| createSharedTempFile(String ext) | File | Creates a unique temporary file in the shared repository temporary directory (Config.REPOSITORY_TEMP_HOME). Use this in multi-node deployments where a shared file system is required. |
createTempFileFromMime
Section titled “createTempFileFromMime”Description:
| Method | Return values | Description |
|---|---|---|
| createTempFileFromMime(String mimeType) | File | Creates a unique temporary file whose extension is resolved from the MIME type via the OpenKM MIME type registry. Falls back to .bin if the MIME type is not found. |
Example:
package com.openkm;
import com.openkm.util.FileUtils;import java.io.File;
public class Test {
public static void main(String[] args) { try { File tmp = FileUtils.createTempFile("pdf"); System.out.println("Temp file: " + tmp.getAbsolutePath());
File tmpFromMime = FileUtils.createTempFileFromMime("application/pdf"); System.out.println("Temp from mime: " + tmpFromMime.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); } }}Directory creation
Section titled “Directory creation”createDateDir
Section titled “createDateDir”Description:
| Method | Return values | Description |
|---|---|---|
| createDateDir(String parent) | File | Creates and returns a yyyy/MM/dd directory structure under the given parent path. The directory is created if it does not already exist. |
createDateUserDir
Section titled “createDateUserDir”Description:
| Method | Return values | Description |
|---|---|---|
| createDateUserDir(String parent) | File | Creates and returns a yyyy/MM/dd/<username> directory structure under the given parent path, where the username is the currently authenticated user. |
Example:
File dateDir = FileUtils.createDateDir("/home/openkm/uploads");System.out.println(dateDir.getAbsolutePath()); // e.g. "/home/openkm/uploads/2024/03/15"File reading and writing
Section titled “File reading and writing”readFileToByteArray
Section titled “readFileToByteArray”Description:
| Method | Return values | Description |
|---|---|---|
| readFileToByteArray(File file) | byte[] | Reads the entire content of a file into a byte array. |
readFileToString
Section titled “readFileToString”Description:
| Method | Return values | Description |
|---|---|---|
| readFileToString(File file) | String | Reads the entire content of a file into a String using UTF-8 encoding. |
readLines
Section titled “readLines”Description:
| Method | Return values | Description |
|---|---|---|
| readLines(File file) | List |
Reads a file into a list of lines using UTF-8 encoding. |
writeStringToFile
Section titled “writeStringToFile”Description:
| Method | Return values | Description |
|---|---|---|
| writeStringToFile(File file, String data) | void | Writes a String to a file using UTF-8 encoding, creating or overwriting the file. |
Example:
package com.openkm;
import com.openkm.util.FileUtils;import java.io.File;import java.util.List;
public class Test {
public static void main(String[] args) { try { File tmp = FileUtils.createTempFile("txt"); FileUtils.writeStringToFile(tmp, "Hello, OpenKM!\nLine 2");
String content = FileUtils.readFileToString(tmp); System.out.println(content);
List<String> lines = FileUtils.readLines(tmp); System.out.println("Lines: " + lines.size()); } catch (Exception e) { e.printStackTrace(); } }}Copy operations
Section titled “Copy operations”copy (InputStream to File)
Section titled “copy (InputStream to File)”Description:
| Method | Return values | Description |
|---|---|---|
| copy(InputStream input, File output) | void | Copies the content of an InputStream to a file. |
copy (Reader to File)
Section titled “copy (Reader to File)”Description:
| Method | Return values | Description |
|---|---|---|
| copy(Reader input, File output) | void | Copies the content of a Reader to a file using UTF-8 encoding. |
copy (File to OutputStream)
Section titled “copy (File to OutputStream)”Description:
| Method | Return values | Description |
|---|---|---|
| copy(File input, OutputStream output) | void | Copies a file to an OutputStream. |
copy (File to File)
Section titled “copy (File to File)”Description:
| Method | Return values | Description |
|---|---|---|
| copy(File input, File output) | void | Copies a file to another file location. |
Example:
package com.openkm;
import com.openkm.util.FileUtils;import java.io.*;
public class Test {
public static void main(String[] args) { try { File source = new File("/home/openkm/source.pdf"); File dest = FileUtils.createTempFile("pdf"); FileUtils.copy(source, dest);
// Stream version InputStream is = new FileInputStream(source); File dest2 = FileUtils.createTempFile("pdf"); FileUtils.copy(is, dest2); is.close(); } catch (Exception e) { e.printStackTrace(); } }}Delete operations
Section titled “Delete operations”deleteQuietly
Section titled “deleteQuietly”Description:
| Method | Return values | Description |
|---|---|---|
| deleteQuietly(File file) | boolean | Deletes a file or directory recursively without throwing exceptions. Returns true if the file was deleted successfully. |
cleanDirectory
Section titled “cleanDirectory”Description:
| Method | Return values | Description |
|---|---|---|
| cleanDirectory(File dir) | void | Deletes all files and subdirectories within a directory, leaving the directory itself in place. |
deleteEmpty
Section titled “deleteEmpty”Description:
| Method | Return values | Description |
|---|---|---|
| deleteEmpty(File file) | void | Deletes the directory only if it is empty. Does nothing if the path is not a directory or is not empty. |
secureDelete
Section titled “secureDelete”Description:
| Method | Return values | Description |
|---|---|---|
| secureDelete(File file) | boolean | Overwrites the file with random bytes before deleting it, reducing the chance of data recovery. Returns true if the file was deleted. |
Example:
File tmp = FileUtils.createTempFile("pdf");// ... write sensitive data to tmp ...boolean deleted = FileUtils.secureDelete(tmp);System.out.println("Securely deleted: " + deleted);Existence checks
Section titled “Existence checks”existFile
Section titled “existFile”Description:
| Method | Return values | Description |
|---|---|---|
| existFile(String file) | boolean | Returns true if the given path exists and is a regular file. |
existFile (File)
Section titled “existFile (File)”Description:
| Method | Return values | Description |
|---|---|---|
| existFile(File file) | boolean | Returns true if the given File exists and is a regular file. |
existDirectory
Section titled “existDirectory”Description:
| Method | Return values | Description |
|---|---|---|
| existDirectory(String dir) | boolean | Returns true if the given path exists and is a directory. |
existDirectory (File)
Section titled “existDirectory (File)”Description:
| Method | Return values | Description |
|---|---|---|
| existDirectory(File dir) | boolean | Returns true if the given File exists and is a directory. |
Example:
if (FileUtils.existFile("/home/openkm/config.properties")) { System.out.println("Config file found");}if (FileUtils.existDirectory("/home/openkm/data")) { System.out.println("Data directory exists");}File listing and counting
Section titled “File listing and counting”listFiles
Section titled “listFiles”Description:
| Method | Return values | Description |
|---|---|---|
| listFiles(File dir, String[] extensions, boolean recursive) | Collection |
Lists files in a directory filtered by extension. Pass null for extensions to list all files. |
- dir: The directory to search.
- extensions: Array of extensions to filter (without dots, e.g.
{"pdf", "docx"}), ornullfor all. - recursive: Whether to include subdirectories.
Example:
import java.util.Collection;import java.io.File;import com.openkm.util.FileUtils;
Collection<File> pdfs = FileUtils.listFiles(new File("/home/openkm/docs"), new String[]{"pdf"}, true);System.out.println("PDF files found: " + pdfs.size());countFiles
Section titled “countFiles”Description:
| Method | Return values | Description |
|---|---|---|
| countFiles(File dir) | int | Recursively counts all files and directories within the given directory. |
MIME type detection
Section titled “MIME type detection”getMimeType (InputStream)
Section titled “getMimeType (InputStream)”Description:
| Method | Return values | Description |
|---|---|---|
| getMimeType(InputStream is) | String | Detects the MIME type from the magic bytes of the stream using Apache Tika. Returns null for unknown types instead of application/octet-stream. |
getMimeType (File)
Section titled “getMimeType (File)”Description:
| Method | Return values | Description |
|---|---|---|
| getMimeType(File file) | String | Detects the MIME type of a file from its magic bytes using Apache Tika. Returns null for unknown types. |
getMediaType
Section titled “getMediaType”Description:
| Method | Return values | Description |
|---|---|---|
| getMediaType(String mimeType) | MediaType | Converts a MIME type string (e.g. "application/pdf") to a Spring MediaType object. Returns MediaType.ALL if the string does not contain a /. |
Example:
package com.openkm;
import com.openkm.util.FileUtils;import java.io.File;
public class Test {
public static void main(String[] args) { try { File file = new File("/home/openkm/document.pdf"); String mime = FileUtils.getMimeType(file); System.out.println("MIME type: " + mime); // "application/pdf" } catch (Exception e) { e.printStackTrace(); } }}