com.hfg.util.FileUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of com_hfg Show documentation
Show all versions of com_hfg Show documentation
com.hfg xml, html, svg, and bioinformatics utility library
package com.hfg.util;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.zip.GZIPOutputStream;
import com.hfg.util.io.StreamUtil;
//------------------------------------------------------------------------------
/**
* General File utility functions.
*
* @author J. Alex Taylor, hairyfatguy.com
*/
//------------------------------------------------------------------------------
// com.hfg XML/HTML Coding Library
//
// This library 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 2.1 of the License, or (at your option) any later version.
//
// This library 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 library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// J. Alex Taylor, President, Founder, CEO, COO, CFO, OOPS hairyfatguy.com
// [email protected]
//------------------------------------------------------------------------------
public class FileUtil
{
private static final String UNIX_SEPARATOR = "/";
private static final String WINDOZE_SEPARATOR = "\\\\";
private static final Pattern sExtensionPattern = Pattern.compile("\\.[^\\.]+$");
//##########################################################################
// PUBLIC FUNCTIONS
//##########################################################################
//---------------------------------------------------------------------------
public static String sanitizeFilename(String inFilename)
{
return inFilename.replaceAll("[\\_\\u0001-\\u001f\"<>\\|\\?\\:\\*/\\\\\\u007f]+", "_");
}
//---------------------------------------------------------------------------
public static boolean rmdir(File inDir)
{
if (inDir.isDirectory())
{
File[] files = inDir.listFiles();
if (files != null)
{
for (int i = 0; i < files.length; i++)
{
File file = files[i];
if (file.isDirectory())
{
rmdir(file);
}
file.delete();
}
}
}
return inDir.delete();
}
//---------------------------------------------------------------------------
/**
Returns the relative file path to inFile1 with respect to inFile2.
Ex: If testFile1 is "dir1/file1.xml" and testFile2 is "dir1/dir2/file2.xml",
this method will return "../file1.xml"
*/
public static String getRelativePath(File inFile1, File inFile2)
{
Stack file1DirStack = getDirStack(inFile1);
Stack file2DirStack = getDirStack(inFile2);
while (file1DirStack.size() > 0
&& file2DirStack.size() > 0
&& file1DirStack.peek().equals(file2DirStack.peek()))
{
file1DirStack.pop();
file2DirStack.pop();
}
StringBuilder relativePath = new StringBuilder(StringUtil.polyString("../", file2DirStack.size()));
if (0 == relativePath.length())
{
relativePath.append("./");
}
while (file1DirStack.size() > 0)
{
File dir = file1DirStack.pop();
if (StringUtil.isSet(dir.getName()))
{
relativePath.append(dir.getName());
relativePath.append("/");
}
}
relativePath.append(inFile1.getName());
return relativePath.toString();
}
//---------------------------------------------------------------------------
/**
Converts file path directory separators to the Unix separator '/'.
@param inFilePath the path to be changed, null ignored
@return the modified path
*/
public static String convertSeparatorsToUnix(String inFilePath)
{
String result = inFilePath;
if (inFilePath != null
&& inFilePath.contains(WINDOZE_SEPARATOR))
{
result = inFilePath.replaceAll(WINDOZE_SEPARATOR, UNIX_SEPARATOR);
}
return result;
}
//---------------------------------------------------------------------------
public static String getNameMinusExtension(File inFile)
{
return getNameMinusExtension(inFile.getName());
}
//---------------------------------------------------------------------------
/**
Returns the specified file's name without its extension. If no extension is
present, the original file name is returned.
(ex: 'foo.txt' would return 'foo')
*/
public static String getNameMinusExtension(String inFilename)
{
String result;
Matcher m = sExtensionPattern.matcher(inFilename);
if (m.find())
{
result = inFilename.substring(0, m.start());
}
else
{
result = inFilename;
}
return result;
}
//---------------------------------------------------------------------------
/**
Returns the specified file's extension or null if no extension was found
(ex: 'foo.txt' would return 'txt').
*/
public static String getExtension(File inFile)
{
String result = null;
Matcher m = sExtensionPattern.matcher(inFile.getName());
if (m.find())
{
result = m.group().substring(1);
}
return result;
}
//---------------------------------------------------------------------------
/**
Writes the specified content to the specified file overwriting any previous content.
*/
public static long write(File inDest, String inContent)
throws IOException
{
return write(inDest, new ByteArrayInputStream(inContent.getBytes()));
}
//---------------------------------------------------------------------------
/**
Writes the specified content to the specified file overwriting any previous content.
*/
public static long write(File inDest, InputStream inContent)
throws IOException
{
long bytesWritten = 0;
if (inContent != null)
{
InputStream inStream = null;
OutputStream outStream = null;
try
{
inStream = new BufferedInputStream(inContent);
outStream = new BufferedOutputStream(new FileOutputStream(inDest));
byte[] buffer = new byte[4 * 1024];
int bytesRead;
while ((bytesRead = inStream.read(buffer)) != -1)
{
outStream.write(buffer, 0, bytesRead);
bytesWritten += bytesRead;
}
}
finally
{
if (inStream != null) inStream.close();
if (outStream != null) outStream.close();
}
}
return bytesWritten;
}
//---------------------------------------------------------------------------
/**
GZIP compresses and writes the specified content to the specified file overwriting any previous content.
*/
public static long writeGzipped(File inDest, InputStream inContent)
throws IOException
{
long bytesWritten = 0;
if (inContent != null)
{
InputStream inStream = null;
OutputStream outStream = null;
try
{
inStream = new BufferedInputStream(inContent);
outStream = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(inDest)));
byte[] buffer = new byte[4 * 1024];
int bytesRead;
while ((bytesRead = inStream.read(buffer)) != -1)
{
outStream.write(buffer, 0, bytesRead);
bytesWritten += bytesRead;
}
}
finally
{
if (inStream != null) inStream.close();
if (outStream != null) outStream.close();
}
}
return bytesWritten;
}
//---------------------------------------------------------------------------
/**
Copies the specified file to the specified target.
*/
public static void copy(File inSrc, File inTarget)
throws IOException
{
if (null == inSrc)
{
throw new IOException("No source file specified!");
}
else if (!inSrc.exists())
{
throw new IOException("Specified source file '" + inSrc + "' doesn't exist!");
}
if (null == inTarget)
{
throw new IOException("No target file specified!");
}
BufferedInputStream readStream = null;
BufferedOutputStream writeStream = null;
try
{
readStream = new BufferedInputStream(new FileInputStream(inSrc));
writeStream = new BufferedOutputStream(new FileOutputStream(inTarget));
byte[] buffer = new byte[8 * 1024];
int bytesRead = 0;
while ((bytesRead = readStream.read(buffer, 0, buffer.length)) != -1)
{
writeStream.write(buffer, 0, bytesRead);
}
}
finally
{
if (readStream != null) readStream.close();
if (writeStream != null) writeStream.close();
}
}
//---------------------------------------------------------------------------
/**
Recursively copies all files and directories within the src directory into the target dir.
*/
public static void copyDirContents(File inSrcDir, File inTargetDir)
throws IOException
{
if (null == inSrcDir)
{
throw new IOException("No source directory specified!");
}
else if (!inSrcDir.exists())
{
throw new IOException("Specified source directory '" + inSrcDir + "' doesn't exist!");
}
else if (!inSrcDir.isDirectory())
{
throw new IOException("Specified source directory '" + inSrcDir + "' isn't a directory!");
}
if (null == inTargetDir)
{
throw new IOException("No target file specified!");
}
else if (!inTargetDir.exists())
{
if (!inTargetDir.mkdirs())
{
throw new IOException("Specified target directory '" + inTargetDir + "' couldn't be created!");
}
}
else if (!inTargetDir.isDirectory())
{
throw new IOException("Specified target directory '" + inTargetDir + "' isn't a directory!");
}
for (File file : inSrcDir.listFiles())
{
if (file.isFile())
{
copy(file, new File(inTargetDir, file.getName()));
}
else if (file.isDirectory())
{
copyDirContents(file, new File(inTargetDir, file.getName()));
}
}
}
//---------------------------------------------------------------------------
public static List readLines(File inFile)
throws IOException
{
checkFileReadability(inFile);
List lines = new ArrayList<>();
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(inFile));
String line;
while ((line = reader.readLine()) != null)
{
lines.add(line);
}
}
finally
{
StreamUtil.close(reader);
}
return lines;
}
//---------------------------------------------------------------------------
private static void checkFileReadability(File inFile)
throws IOException
{
if (null == inFile)
{
throw new IOException("No file specified!");
}
else if (! inFile.exists())
{
throw new IOException("The file " + StringUtil.singleQuote(inFile.getPath()) + " doesn't exist!");
}
else if (!inFile.canRead())
{
throw new IOException("The file " + StringUtil.singleQuote(inFile.getPath()) + " cannot be read!");
}
}
//---------------------------------------------------------------------------
private static Stack getDirStack(File inFile)
{
Stack dirStack = new Stack<>();
File file = inFile;
while ((file = file.getParentFile()) != null)
{
dirStack.push(file);
}
return dirStack;
}
}