- Java file util class
- Java file open, read, and write utilities
- My Java file utilities class
- Java file utilities discussion
- Apache Commons IO library
- Java file util class
- FileUtils
- validateFile
- copy
- deleteFileOrDirectory
- assureDirectoryExists
- assureDirectoryExists
- subtractRootPath
- getExtension
- getHashPath
- writeDirHashFile
- readDirHashFile
- moveFile
- renameFile
- createTempDirectory
Java file util class
Path testFile = Paths.get(«C:\\Users\\jleom\\Desktop\\java\\javarush task\\test.txt»); Path testFile2 = Paths.get(«C:\\Users\\jleom\\Desktop»); System.out.println(testFile.relativize(testFile2));
Класс Path и класс Paths предназначены для работы с файловой системой в Java, однако они предоставляют разные функции и методы. Path — это интерфейс, который определяет методы для работы с путями к файлам и каталогам в файловой системе. Он предоставляет ряд методов для работы с путями, таких как resolve(), relativize(), getParent(), getFileName(), toAbsolutePath() и другие. Paths — это утилитный класс, который предоставляет статические методы для создания экземпляров класса Path. Он не имеет методов для работы с путями напрямую, но предоставляет методы для создания экземпляров Path из строковых значений или URI. Еще методы по классу Paths: getFileSystem(): возвращает объект FileSystem, представляющий файловую систему, которой принадлежит данный путь. getDefault(): возвращает объект FileSystem, представляющий файловую систему по умолчанию. getTempDirectory(): возвращает объект типа Path, представляющий временный каталог. getHomeDirectory(): возвращает объект типа Path, представляющий домашний каталог пользователя. exists(Path path, LinkOption. options): проверяет, существует ли файл или каталог, представленный указанным путем. Класс Paths удобен для работы с файловой системой, так как он предоставляет простой и удобный API для работы с путями.
Надо добавить в статью, Paths.get был в 8 Java. Потом появился Path.of. Если у вас не работает Path.of (версия Java не позволяет), только тогда нужен Paths.get
Java file open, read, and write utilities
Java file utilities FAQ: Do you have any Java file utilities you can share?
As I was working on another Java/Swing application this weekend, I ran across my «Java file utilities» class, and I thought I’d share that class here today. It’s nothing too major, but it does include Java methods that let you open, read, write, and copy files using Java.
My Java file utilities class
Without any further introduction, here’s the source code for my Java file utilities class:
package com.devdaily.utils; import java.io.*; import java.util.*; /** * Copyright 2010 Alvin J. Alexander, devdaily.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * A copy of the GNU Lesser General Public License is available at this URL: * http://www.gnu.org/licenses/lgpl.txt * */ public class FileUtils < /** * Opens and reads a file, and returns the contents as one String. */ public static String readFileAsString(String filename) throws IOException < BufferedReader reader = new BufferedReader(new FileReader(filename)); String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) < sb.append(line + "\n"); >reader.close(); return sb.toString(); > /** * Open and read a file, and return the lines in the file as a list of * Strings. */ public static List readFileAsListOfStrings(String filename) throws Exception < Listrecords = new ArrayList(); BufferedReader reader = new BufferedReader(new FileReader(filename)); String line; while ((line = reader.readLine()) != null) < records.add(line); >reader.close(); return records; > /** * Reads a "properties" file, and returns it as a Map (a collection of key/value pairs). * * @param filename * @param delimiter * @return * @throws Exception */ public static Map readPropertiesFileAsMap(String filename, String delimiter) throws Exception < Mapmap = new HashMap(); BufferedReader reader = new BufferedReader(new FileReader(filename)); String line; while ((line = reader.readLine()) != null) < if (line.trim().length()==0) continue; if (line.charAt(0)=='#') continue; // assumption here is that proper lines are like "String : http://xxx.yyy.zzz/foo/bar", // and the ":" is the delimiter int delimPosition = line.indexOf(delimiter); String key = line.substring(0, delimPosition-1).trim(); String value = line.substring(delimPosition+1).trim(); map.put(key, value); >reader.close(); return map; > /** * Read a Java properties file and return it as a Properties object. */ public static Properties readPropertiesFile(String canonicalFilename) throws IOException < Properties properties = new Properties(); properties.load(new FileInputStream(canonicalFilename)); return properties; >/** * Save the given text to the given filename. * @param canonicalFilename Like /Users/al/foo/bar.txt * @param text All the text you want to save to the file as one String. * @throws IOException */ public static void writeFile(String canonicalFilename, String text) throws IOException < File file = new File (canonicalFilename); BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(text); out.close(); >/** * Write an array of bytes to a file. Presumably this is binary data; for plain text * use the writeFile method. */ public static void writeFileAsBytes(String fullPath, byte[] bytes) throws IOException < OutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fullPath)); InputStream inputStream = new ByteArrayInputStream(bytes); int token = -1; while((token = inputStream.read()) != -1) < bufferedOutputStream.write(token); >bufferedOutputStream.flush(); bufferedOutputStream.close(); inputStream.close(); > public static void copyFile(File source, File destination) throws IOException < //if (!source.isFile() || !dest.isFile()) return false; byte[] buffer = new byte[100000]; BufferedInputStream bufferedInputStream = null; BufferedOutputStream bufferedOutputStream = null; try < bufferedInputStream = new BufferedInputStream(new FileInputStream(source)); bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destination)); int size; while ((size = bufferedInputStream.read(buffer)) >-1) < bufferedOutputStream.write(buffer, 0, size); >> catch (IOException e) < // TODO may want to do something more here throw e; >finally < try < if (bufferedInputStream != null) < bufferedInputStream.close(); >if (bufferedOutputStream != null) < bufferedOutputStream.flush(); bufferedOutputStream.close(); >> catch (IOException ioe) < // TODO may want to do something more here throw ioe; >> > >
Java file utilities discussion
As you can see from that code, this class provides the following Java methods:
- A Java file open and read method
- A Java file write method to write text to a file
- A Java file write method to write bytes to a file
- A Java properties file reading method
- A Java properties Map method
- A Java file copy method
I hope this Java file utilities class helps in your own Java programming efforts, and it is shared freely here under the terms of the GNU LGPL.
Apache Commons IO library
A few people wrote to suggest that I mention the Apache Commons IO library, and that’s a great suggestion. I didn’t mean to slight them in any way, I was just trying to share some Java code here that demonstrated these file-related techniques. I’m a big fan of the Commons’ libraries, and have used them in many projects.
I generally use my own library in Java/Swing/GUI projects where I’m giving users a collection of jar files, and I like to keep my filesize footprint down, but these days even adding the 1.2MB Commons IO library isn’t a big deal.
Java file util class
java.lang.Object
oracle.stellent.wcm.common.io.FileUtils
public class FileUtils
Constructor Summary | |
---|---|
FileUtils() |
Method Summary | |
---|---|
static boolean | assureDirectoryExists(java.io.File dir, ILog log) Make sure that the directory exists, creating it if necessary |
static boolean | assureDirectoryExists(java.lang.String dirPath, ILog log) Make sure that the directory exists, creating it if necessary |
static void | copy(java.io.File src, java.io.File dst) Copies src file to dst file. |
static java.io.File | createTempDirectory(java.lang.String prefix, java.lang.String suffix, java.io.File parentDir) |
static boolean | deleteFileOrDirectory(java.io.File dir) Deletes all files and subdirectories under dir. |
static java.lang.String | getExtension(java.lang.String path) |
static java.io.File | getHashPath(java.lang.String dDocName, java.util.regex.Pattern dirHash) Return a directory path to the dDocName using the dirHash pattern. |
static void | moveFile(java.io.File source, java.io.File destination) Move the source file to the destination file |
static java.lang.String | readDirHashFile(java.io.File root) Read the dirHash Pattern in from the root directory. |
static void | renameFile(java.io.File fromFile, java.io.File toFile, boolean overwrite) Referenced from Content Server source; refer to intradoc.common.FileUtils#renameFileEx(java.lang.String, java.lang.String, int) |
static java.io.File | subtractRootPath(java.io.File rootPath, java.io.File fullPath) extract the part after the rootPath from the fullPath |
static boolean | validateFile(java.io.File file, boolean isDirectory) Validate a file before accessing. |
static void | writeDirHashFile(java.lang.String dirHash, java.io.File root) Write the string dirHash into a file «dirHash.txt» in the root directory if the text is null or blank, the file if present will be removed. |
Methods inherited from class java.lang.Object |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
FileUtils
validateFile
public static boolean validateFile(java.io.File file, boolean isDirectory)
Validate a file before accessing. Determines if the file exists, is readable and is a file object. Parameters: file — a reference to a physical file isDirectory — if true, validate this is a directory; false validate this is a file Returns: true if the file exists and can be read
copy
public static void copy(java.io.File src, java.io.File dst) throws java.io.IOException
Copies src file to dst file. If the dst file does not exist, it is created Parameters: src — dst — Throws: java.io.IOException
deleteFileOrDirectory
public static boolean deleteFileOrDirectory(java.io.File dir)
Deletes all files and subdirectories under dir. If a deletion fails, the method stops attempting to delete and returns false. Parameters: dir — Returns: Returns true if all deletions were successful.
assureDirectoryExists
Make sure that the directory exists, creating it if necessary Parameters: dirPath — directory path log — ILog reference if logging is desired, if not desired pass in null Returns: true if exists, or was created, false if cannot create
assureDirectoryExists
Make sure that the directory exists, creating it if necessary Parameters: dir — directory path log — ILog reference if logging is desired, if not desired pass in null Returns: true if exists, or was created, false if cannot create
subtractRootPath
public static java.io.File subtractRootPath(java.io.File rootPath, java.io.File fullPath)
extract the part after the rootPath from the fullPath Parameters: rootPath — first part of path (ie: /scs/weblayout/) fullPath — full path (ie: /scs/weblayout/groups/public/documents/adhr/) Returns: part after the rootPath (ie: groups/public/documents/adhr/)
getExtension
public static java.lang.String getExtension(java.lang.String path)
getHashPath
public static java.io.File getHashPath(java.lang.String dDocName, java.util.regex.Pattern dirHash)
Return a directory path to the dDocName using the dirHash pattern. In the pattern any areas surrounded by parenthesis are used to create directory levels Parameters: dDocName — Content Server’s dDocName dirHash — precompiled regular expression Returns:
writeDirHashFile
public static void writeDirHashFile(java.lang.String dirHash, java.io.File root) throws java.io.IOException
Write the string dirHash into a file «dirHash.txt» in the root directory if the text is null or blank, the file if present will be removed. By convention, you should set the root directory to be the parent of the metadata/content directory Parameters: dirHash — text to write into the file root — directory where the «dirHash.txt» file is located Throws: java.io.IOException
readDirHashFile
public static java.lang.String readDirHashFile(java.io.File root) throws java.io.IOException
Read the dirHash Pattern in from the root directory. By convention, you should set the root directory to be the parent of the metadata/content directory Parameters: root — directory where the «dirHash.txt» file is located Returns: compiled Pattern or null Throws: java.io.IOException
moveFile
public static void moveFile(java.io.File source, java.io.File destination) throws java.io.IOException
Move the source file to the destination file Parameters: source — the source file destination — the destination Throws: java.io.IOException
renameFile
public static void renameFile(java.io.File fromFile, java.io.File toFile, boolean overwrite) throws java.io.IOException
Referenced from Content Server source; refer to intradoc.common.FileUtils#renameFileEx(java.lang.String, java.lang.String, int) Parameters: fromFile — the source file toFile — the destination overwrite — true to overwrite the destination if it exists Throws: java.io.IOException
createTempDirectory
public static java.io.File createTempDirectory(java.lang.String prefix, java.lang.String suffix, java.io.File parentDir) throws java.io.IOException
Copyright © 2010, 2011, Oracle and/or its affiliates. All rights reserved.