Java Tutorial/File/File Utilities
Содержание
- 1 Avoiding Overwriting a File
- 2 Compare binary files
- 3 Copying Files using FileChannel
- 4 Count files in a directory (including files in all subdirectories)
- 5 Ensuring a File Exists
- 6 Extract File Extension
- 7 Format Size
- 8 Get file date and time
- 9 Get File Name Suffix
- 10 Move File
- 11 Remove File Name Suffix
- 12 Rename To Temporary Name
- 13 Return readable file size with selected value measure
- 14 Strip File Extension
- 15 Utility class for synchronizing files/directories
Avoiding Overwriting a File
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class MainClass {
public static void main(String[] Args) {
String filepath = "C:/myFile.txt";
File aFile = new File(filepath);
FileOutputStream outputFile = null;
if (aFile.isFile()) {
File newFile = aFile;
do {
String name = newFile.getName();
int period = name.indexOf(".");
newFile = new File(newFile.getParent(), name.substring(0, period) + "_old"
+ name.substring(period));
} while (newFile.exists());
aFile.renameTo(newFile);
}
try {
outputFile = new FileOutputStream(aFile);
System.out.println("myFile.txt output stream created");
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
}
}
Compare binary files
/**
* Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
*
* Project: OpenSubsystems
*
* $Id: FileUtils.java,v 1.12 2007/02/01 07:18:32 bastafidli Exp $
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
/**
* Collection of methods to make work with files easier.
*
* @version $Id: FileUtils.java,v 1.12 2007/02/01 07:18:32 bastafidli Exp $
* @author Miro Halas
* @code.reviewer Miro Halas
* @code.reviewed 1.7 2006/05/21 03:45:37 bastafidli
*/
public class FileUtils
{
// Configuration settings ///////////////////////////////////////////////////
/**
* Default 10 digit file storage distribution array. This means that if I
* want to name file as 10 digit number e.g. number 123 as 0000000123 or
* number 123456789 as 01234567890. Then the path constructed from number
* 1234567890 using distribution 2/2/2/4 would be 12/34/56/0123456789
*/
public static final int[] DEFAULT_STRORAGE_TREE_DISTRIBUTION = {2, 2, 2, 4};
/**
* How big buffer to use to process files.
*/
public static final int BUFFER_SIZE = 65536;
// Cached values ////////////////////////////////////////////////////////////
/**
* Temporary directory to use. It is guarantee that it ends with \ (or /)
*/
protected static String s_strTempDirectory;
// Constructors /////////////////////////////////////////////////////////////
/**
* Move file to a new location. If the destination is on different volume,
* this file will be copied and then original file will be deleted.
* If the destination already exists, this method renames it with different
* name and leaves it in that directory and moves the new file along side
* the renamed one.
*
* @param flCurrent - file to move
* @param flDestination - destination file
* @throws IOException - error message
* @throws OSSException - error message
*/
public static void moveFile(
File flCurrent,
File flDestination
) throws IOException
{
// Make sure that the source exist, it might be already moved from
// a directory and we just don"t know about it
if (flCurrent.exists())
{
// Next check if the destination file exists
if (flDestination.exists())
{
// If the destination exists, that means something went wrong
// Rename the destination file under temporaty name and try to
// move the new file instead of it
renameToTemporaryName(flDestination, "old");
}
// Make sure the directory exists and if not create it
File flFolder;
flFolder = flDestination.getParentFile();
if ((flFolder != null) && (!flFolder.exists()))
{
if (!flFolder.mkdirs())
{
// Do not throw the exception if the directory already exists
// because it was created meanwhile for example by a different
// thread
if (!flFolder.exists())
{
throw new IOException("Cannot create directory " + flFolder);
}
}
}
// Now everything should exist so try to rename the file first
// After testing, this renames files even between volumes C to H
// so we don"t have to do anything else on Windows but we still
// have to handle erro on Unix
if (!flCurrent.renameTo(flDestination))
{
// Try to copy and delete since the rename doesn"t work on Solaris
// between file systems
copyFile(flCurrent, flDestination);
// Now delete the file
if (!flCurrent.delete())
{
// Delete the destination file first since we haven"t really moved
// the file
flDestination.delete();
throw new IOException("Cannot delete already copied file " + flCurrent);
}
}
}
}
/**
* Copy the current file to the destination file.
*
* @param flCurrent - source file
* @param flDestination - destination file
* @throws IOException - error message
* @throws OSSException - error message
*/
public static void copyFile(
File flCurrent,
File flDestination
) throws IOException
{
// Make sure the directory exists and if not create it
File flFolder;
flFolder = flDestination.getParentFile();
if ((flFolder != null) && (!flFolder.exists()))
{
if (!flFolder.mkdirs())
{
// Do not throw the exception if the directory already exists
// because it was created meanwhile for example by a different
// thread
if (!flFolder.exists())
{
throw new IOException("Cannot create directory " + flFolder);
}
}
}
// FileChannel srcChannel = null;
// FileChannel dstChannel = null;
FileInputStream finInput = null;
//MHALAS: This code is not working reliably on Solaris 8 with 1.4.1_01
// Getting exceptions from native code
/*
// Create channel on the source
srcChannel = new FileInputStream(flCurrent).getChannel();
// Create channel on the destination
dstChannel = new FileOutputStream(flDestination).getChannel();
// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
Don"t forget to close the channels if you enable this code again
*/
try
{
finInput = new FileInputStream(flCurrent);
}
catch (IOException ioExec)
{
if (finInput != null)
{
try
{
finInput.close();
}
catch (Throwable thr)
{
}
}
throw ioExec;
}
FileUtils.copyStreamToFile(finInput, flDestination);
}
/**
* Rename the file to temporaty name with given prefix
*
* @param flFileToRename - file to rename
* @param strPrefix - prefix to use
* @throws IOException - error message
*/
public static void renameToTemporaryName(
File flFileToRename,
String strPrefix
) throws IOException
{
assert strPrefix != null : "Prefix cannot be null.";
String strParent;
StringBuffer sbBuffer = new StringBuffer();
File flTemp;
int iIndex = 0;
strParent = flFileToRename.getParent();
// Generate new name for the file in a deterministic way
do
{
iIndex++;
sbBuffer.delete(0, sbBuffer.length());
if (strParent != null)
{
sbBuffer.append(strParent);
sbBuffer.append(File.separatorChar);
}
sbBuffer.append(strPrefix);
sbBuffer.append("_");
sbBuffer.append(iIndex);
sbBuffer.append("_");
sbBuffer.append(flFileToRename.getName());
flTemp = new File(sbBuffer.toString());
}
while (flTemp.exists());
// Now we should have unique name
if (!flFileToRename.renameTo(flTemp))
{
throw new IOException("Cannot rename " + flFileToRename.getAbsolutePath()
+ " to " + flTemp.getAbsolutePath());
}
}
/**
* Delete all files and directories in directory but do not delete the
* directory itself.
*
* @param strDir - string that specifies directory to delete
* @return boolean - sucess flag
*/
public static boolean deleteDirectoryContent(
String strDir
)
{
return ((strDir != null) && (strDir.length() > 0))
? deleteDirectoryContent(new File(strDir)) : false;
}
/**
* Delete all files and directories in directory but do not delete the
* directory itself.
*
* @param fDir - directory to delete
* @return boolean - sucess flag
*/
public static boolean deleteDirectoryContent(
File fDir
)
{
boolean bRetval = false;
if (fDir != null && fDir.isDirectory())
{
File[] files = fDir.listFiles();
if (files != null)
{
bRetval = true;
boolean dirDeleted;
for (int index = 0; index < files.length; index++)
{
if (files[index].isDirectory())
{
// TODO: Performance: Implement this as a queue where you add to
// the end and take from the beginning, it will be more efficient
// than the recursion
dirDeleted = deleteDirectoryContent(files[index]);
if (dirDeleted)
{
bRetval = bRetval && files[index].delete();
}
else
{
bRetval = false;
}
}
else
{
bRetval = bRetval && files[index].delete();
}
}
}
}
return bRetval;
}
/**
* Deletes all files and subdirectories under the specified directory including
* the specified directory
*
* @param strDir - string that specifies directory to be deleted
* @return boolean - true if directory was successfully deleted
*/
public static boolean deleteDir(
String strDir
)
{
return ((strDir != null) && (strDir.length() > 0))
? deleteDir(new File(strDir)) : false;
}
/**
* Deletes all files and subdirectories under the specified directory including
* the specified directory
*
* @param fDir - directory to be deleted
* @return boolean - true if directory was successfully deleted
*/
public static boolean deleteDir(
File fDir
)
{
boolean bRetval = false;
if (fDir != null && fDir.exists())
{
bRetval = deleteDirectoryContent(fDir);
if (bRetval)
{
bRetval = bRetval && fDir.delete();
}
}
return bRetval;
}
/**
* Compare binary files. Both files must be files (not directories) and exist.
*
* @param first - first file
* @param second - second file
* @return boolean - true if files are binery equal
* @throws IOException - error in function
*/
public boolean isFileBinaryEqual(
File first,
File second
) throws IOException
{
// TODO: Test: Missing test
boolean retval = false;
if ((first.exists()) && (second.exists())
&& (first.isFile()) && (second.isFile()))
{
if (first.getCanonicalPath().equals(second.getCanonicalPath()))
{
retval = true;
}
else
{
FileInputStream firstInput = null;
FileInputStream secondInput = null;
BufferedInputStream bufFirstInput = null;
BufferedInputStream bufSecondInput = null;
try
{
firstInput = new FileInputStream(first);
secondInput = new FileInputStream(second);
bufFirstInput = new BufferedInputStream(firstInput, BUFFER_SIZE);
bufSecondInput = new BufferedInputStream(secondInput, BUFFER_SIZE);
int firstByte;
int secondByte;
while (true)
{
firstByte = bufFirstInput.read();
secondByte = bufSecondInput.read();
if (firstByte != secondByte)
{
break;
}
if ((firstByte < 0) && (secondByte < 0))
{
retval = true;
break;
}
}
}
finally
{
try
{
if (bufFirstInput != null)
{
bufFirstInput.close();
}
}
finally
{
if (bufSecondInput != null)
{
bufSecondInput.close();
}
}
}
}
}
return retval;
}
/**
* Get path which represents temporary directory. It is guarantee that it
* ends with \ (or /).
*
* @return String
*/
public static String getTemporaryDirectory(
)
{
return s_strTempDirectory;
}
/**
* Copy any input stream to output file. Once the data will be copied
* the stream will be closed.
*
* @param input - InputStream to copy from
* @param output - File to copy to
* @throws IOException - error in function
* @throws OSSMultiException - double error in function
*/
public static void copyStreamToFile(
InputStream input,
File output
) throws IOException
{
FileOutputStream foutOutput = null;
// open input file as stream safe - it can throw some IOException
try
{
foutOutput = new FileOutputStream(output);
}
catch (IOException ioExec)
{
if (foutOutput != null)
{
try
{
foutOutput.close();
}
catch (IOException ioExec2)
{
}
}
throw ioExec;
}
// all streams including os are closed in copyStreamToStream function
// in any case
copyStreamToStream(input, foutOutput);
}
/**
* Copy any input stream to output stream. Once the data will be copied
* both streams will be closed.
*
* @param input - InputStream to copy from
* @param output - OutputStream to copy to
* @throws IOException - io error in function
* @throws OSSMultiException - double error in function
*/
public static void copyStreamToStream(
InputStream input,
OutputStream output
) throws IOException
{
InputStream is = null;
OutputStream os = null;
int ch;
try
{
if (input instanceof BufferedInputStream)
{
is = input;
}
else
{
is = new BufferedInputStream(input);
}
if (output instanceof BufferedOutputStream)
{
os = output;
}
else
{
os = new BufferedOutputStream(output);
}
while ((ch = is.read()) != -1)
{
os.write(ch);
}
os.flush();
}
finally
{
IOException exec1 = null;
IOException exec2 = null;
try
{
// because this close can throw exception we do next close in
// finally statement
if (os != null)
{
try
{
os.close();
}
catch (IOException exec)
{
exec1 = exec;
}
}
}
finally
{
if (is != null)
{
try
{
is.close();
}
catch (IOException exec)
{
exec2 = exec;
}
}
}
if ((exec1 != null) && (exec2 != null))
{
throw exec1;
}
else if (exec1 != null)
{
throw exec1;
}
else if (exec2 != null)
{
throw exec2;
}
}
}
}
Copying Files using FileChannel
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String[] args) throws Exception {
File fromFile = new File("fromFile.txt");
File toFile = new File("toFile.txt");
FileInputStream inFile = new FileInputStream(fromFile);
FileOutputStream outFile = new FileOutputStream(toFile);
FileChannel inChannel = inFile.getChannel();
FileChannel outChannel = outFile.getChannel();
int bytesWritten = 0;
long byteCount = inChannel.size();
while (bytesWritten < byteCount) {
bytesWritten += inChannel.transferTo(bytesWritten, byteCount - bytesWritten, outChannel);
}
inFile.close();
outFile.close();
}
}
Count files in a directory (including files in all subdirectories)
import java.io.File;
import java.io.IOException;
public class Utils {
/**
* Count files in a directory (including files in all subdirectories)
* @param directory the directory to start in
* @return the total number of files
*/
public static int countFilesInDirectory(File directory) {
int count = 0;
for (File file : directory.listFiles()) {
if (file.isFile()) {
count++;
}
if (file.isDirectory()) {
count += countFilesInDirectory(file);
}
}
return count;
}
}
Ensuring a File Exists
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class GuaranteeAFile {
public static void main(String[] args) {
String filename = "C:/myFile.txt";
File aFile = new File(filename);
if (aFile.isDirectory()) {
System.out.println("The path " + aFile.getPath()
+ " does not specify a file. Program aborted.");
System.exit(1);
}
if (!aFile.isFile()) {
aFile = aFile.getAbsoluteFile();
File parentDir = new File(aFile.getParent());
if (!parentDir.exists()) {
parentDir.mkdirs();
}
}
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream(aFile, true);
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
}
}
Extract File Extension
/**
*
* The ObjectStyle Group Software License, version 1.1
* ObjectStyle Group - http://objectstyle.org/
*
* Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
* of the software. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if any,
* must include the following acknowlegement:
* "This product includes software developed by independent contributors
* and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
* or promote products derived from this software without prior written
* permission. For written permission, email
* "andrus at objectstyle dot org".
*
* 5. Products derived from this software may not be called "ObjectStyle"
* or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
* names without prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many
* individuals and hosted on ObjectStyle Group web site. For more
* information on the ObjectStyle Group, please see
* <http://objectstyle.org/>.
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ruparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Contains various unorganized static utility methods used across Cayenne.
*
* @author Andrei Adamchik
*/
public class Util {
/**
* Extracts extension from the file name. Dot is not included in the returned string.
*/
public static String extractFileExtension(String fileName) {
int dotInd = fileName.lastIndexOf(".");
// if dot is in the first position,
// we are dealing with a hidden file rather than an extension
return (dotInd > 0 && dotInd < fileName.length()) ? fileName
.substring(dotInd + 1) : null;
}
}
Format Size
/*
* Copyright (C) 2001-2003 Colin Bell
* colbell@users.sourceforge.net
*
* 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
*/
import java.io.*;
import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* General purpose utilities functions.
*
* @author
*/
public class Utilities
{
public static String formatSize(long longSize, int decimalPos)
{
NumberFormat fmt = NumberFormat.getNumberInstance();
if (decimalPos >= 0)
{
fmt.setMaximumFractionDigits(decimalPos);
}
final double size = longSize;
double val = size / (1024 * 1024);
if (val > 1)
{
return fmt.format(val).concat(" MB");
}
val = size / 1024;
if (val > 10)
{
return fmt.format(val).concat(" KB");
}
return fmt.format(val).concat(" bytes");
}
}
Get file date and time
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
/*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2005 Marc Eppelmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Provides general global file utility methods
*
* @author marc.eppelmann
*/
class FileUtil
{
//~ Constructors ***********************************************************************
/**
* Creates a new FileUtil object.
*/
public FileUtil()
{
}
//~ Methods ****************************************************************************
/**
* Gets the content from a File as StringArray List.
*
* @param fileName A file to read from.
* @return List of individual line of the specified file. List may be empty but not
* null.
* @throws IOException
*/
public static ArrayList getFileContent(String fileName)
throws IOException
{
ArrayList result = new ArrayList();
File aFile = new File(fileName);
if (!aFile.isFile())
{
//throw new IOException( fileName + " is not a regular File" );
return result; // None
}
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(aFile));
}
catch (FileNotFoundException e1)
{
// TODO handle Exception
e1.printStackTrace();
return result;
}
String aLine = null;
while ((aLine = reader.readLine()) != null)
{
result.add(aLine + "\n");
}
reader.close();
return result;
}
/**
* Searches case sensitively, and returns true if the given SearchString occurs in the
* first File with the given Filename.
*
* @param aFileName A files name
* @param aSearchString the string search for
* @return true if found in the file otherwise false
*/
public static boolean fileContains(String aFileName, String aSearchString)
{
return (fileContains(aFileName, aSearchString, false));
}
/**
* Tests if the given File contains the given Search String
*
* @param aFileName A files name
* @param aSearchString the String to search for
* @param caseInSensitiveSearch If false the Search is casesensitive
* @return true if found in the file otherwise false
*/
public static boolean fileContains(String aFileName, String aSearchString,
boolean caseInSensitiveSearch)
{
boolean result = false;
String searchString = caseInSensitiveSearch
? aSearchString.toLowerCase() : aSearchString;
ArrayList fileContent = new ArrayList();
try
{
fileContent = getFileContent(aFileName);
}
catch (IOException e)
{
// TODO handle Exception
e.printStackTrace();
}
Iterator linesIter = fileContent.iterator();
while (linesIter.hasNext())
{
String currentline = (String) linesIter.next();
if (caseInSensitiveSearch)
{
currentline = currentline.toLowerCase();
}
if (currentline.indexOf(searchString) > -1)
{
result = true;
break;
}
}
return result;
}
/**
* Gets file date and time.
*
* @param url The URL of the file for which date and time will be returned.
* @return Returns long value which is the date and time of the file. If any error
* occures returns -1 (=no file date and time available).
*/
public static long getFileDateTime(URL url)
{
if (url == null)
{
return -1;
}
String fileName = url.getFile();
if (fileName.charAt(0) == "/" || fileName.charAt(0) == "\\")
{
fileName = fileName.substring(1, fileName.length());
}
try
{
File file = new File(fileName);
// File name must be a file or a directory.
if (!file.isDirectory() && !file.isFile())
{
return -1;
}
return file.lastModified();
}
catch (java.lang.Exception e)
{ // Trap all Exception based exceptions and return -1.
return -1;
}
}
public static String[] getFileNames(String dirPath) throws Exception
{
return getFileNames(dirPath, null);
}
public static String[] getFileNames(String dirPath, FilenameFilter fileNameFilter) throws Exception
{
String fileNames[] = null;
File dir = new File(dirPath);
if (dir.isDirectory())
{
if (fileNameFilter != null)
{
fileNames = dir.list(fileNameFilter);
}
else
{
fileNames = dir.list();
}
}
return fileNames;
}
/**
* Test main
*
* @param args
*/
public static void main(String[] args)
{
}
}
Get File Name Suffix
/*
* Copyright (C) 2001-2003 Colin Bell
* colbell@users.sourceforge.net
*
* 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
*/
import java.io.*;
import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* General purpose utilities functions.
*
* @author
*/
public class Utilities
{
/**
* Return the suffix of the passed file name.
*
* @param fileName File name to retrieve suffix for.
*
* @return Suffix for <TT>fileName</TT> or an empty string
* if unable to get the suffix.
*
* @throws IllegalArgumentException if <TT>null</TT> file name passed.
*/
public static String getFileNameSuffix(String fileName)
{
if (fileName == null)
{
throw new IllegalArgumentException("file name == null");
}
int pos = fileName.lastIndexOf(".");
if (pos > 0 && pos < fileName.length() - 1)
{
return fileName.substring(pos + 1);
}
return "";
}
}
Move File
/**
* Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
*
* Project: OpenSubsystems
*
* $Id: FileUtils.java,v 1.12 2007/02/01 07:18:32 bastafidli Exp $
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
/**
* Collection of methods to make work with files easier.
*
* @version $Id: FileUtils.java,v 1.12 2007/02/01 07:18:32 bastafidli Exp $
* @author Miro Halas
* @code.reviewer Miro Halas
* @code.reviewed 1.7 2006/05/21 03:45:37 bastafidli
*/
public class FileUtils
{
// Configuration settings ///////////////////////////////////////////////////
/**
* Default 10 digit file storage distribution array. This means that if I
* want to name file as 10 digit number e.g. number 123 as 0000000123 or
* number 123456789 as 01234567890. Then the path constructed from number
* 1234567890 using distribution 2/2/2/4 would be 12/34/56/0123456789
*/
public static final int[] DEFAULT_STRORAGE_TREE_DISTRIBUTION = {2, 2, 2, 4};
/**
* How big buffer to use to process files.
*/
public static final int BUFFER_SIZE = 65536;
// Cached values ////////////////////////////////////////////////////////////
/**
* Temporary directory to use. It is guarantee that it ends with \ (or /)
*/
protected static String s_strTempDirectory;
// Constructors /////////////////////////////////////////////////////////////
/**
* Move file to a new location. If the destination is on different volume,
* this file will be copied and then original file will be deleted.
* If the destination already exists, this method renames it with different
* name and leaves it in that directory and moves the new file along side
* the renamed one.
*
* @param flCurrent - file to move
* @param flDestination - destination file
* @throws IOException - error message
* @throws OSSException - error message
*/
public static void moveFile(
File flCurrent,
File flDestination
) throws IOException
{
// Make sure that the source exist, it might be already moved from
// a directory and we just don"t know about it
if (flCurrent.exists())
{
// Next check if the destination file exists
if (flDestination.exists())
{
// If the destination exists, that means something went wrong
// Rename the destination file under temporaty name and try to
// move the new file instead of it
renameToTemporaryName(flDestination, "old");
}
// Make sure the directory exists and if not create it
File flFolder;
flFolder = flDestination.getParentFile();
if ((flFolder != null) && (!flFolder.exists()))
{
if (!flFolder.mkdirs())
{
// Do not throw the exception if the directory already exists
// because it was created meanwhile for example by a different
// thread
if (!flFolder.exists())
{
throw new IOException("Cannot create directory " + flFolder);
}
}
}
// Now everything should exist so try to rename the file first
// After testing, this renames files even between volumes C to H
// so we don"t have to do anything else on Windows but we still
// have to handle erro on Unix
if (!flCurrent.renameTo(flDestination))
{
// Try to copy and delete since the rename doesn"t work on Solaris
// between file systems
copyFile(flCurrent, flDestination);
// Now delete the file
if (!flCurrent.delete())
{
// Delete the destination file first since we haven"t really moved
// the file
flDestination.delete();
throw new IOException("Cannot delete already copied file " + flCurrent);
}
}
}
}
/**
* Copy the current file to the destination file.
*
* @param flCurrent - source file
* @param flDestination - destination file
* @throws IOException - error message
* @throws OSSException - error message
*/
public static void copyFile(
File flCurrent,
File flDestination
) throws IOException
{
// Make sure the directory exists and if not create it
File flFolder;
flFolder = flDestination.getParentFile();
if ((flFolder != null) && (!flFolder.exists()))
{
if (!flFolder.mkdirs())
{
// Do not throw the exception if the directory already exists
// because it was created meanwhile for example by a different
// thread
if (!flFolder.exists())
{
throw new IOException("Cannot create directory " + flFolder);
}
}
}
// FileChannel srcChannel = null;
// FileChannel dstChannel = null;
FileInputStream finInput = null;
//MHALAS: This code is not working reliably on Solaris 8 with 1.4.1_01
// Getting exceptions from native code
/*
// Create channel on the source
srcChannel = new FileInputStream(flCurrent).getChannel();
// Create channel on the destination
dstChannel = new FileOutputStream(flDestination).getChannel();
// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
Don"t forget to close the channels if you enable this code again
*/
try
{
finInput = new FileInputStream(flCurrent);
}
catch (IOException ioExec)
{
if (finInput != null)
{
try
{
finInput.close();
}
catch (Throwable thr)
{
}
}
throw ioExec;
}
FileUtils.copyStreamToFile(finInput, flDestination);
}
/**
* Rename the file to temporaty name with given prefix
*
* @param flFileToRename - file to rename
* @param strPrefix - prefix to use
* @throws IOException - error message
*/
public static void renameToTemporaryName(
File flFileToRename,
String strPrefix
) throws IOException
{
assert strPrefix != null : "Prefix cannot be null.";
String strParent;
StringBuffer sbBuffer = new StringBuffer();
File flTemp;
int iIndex = 0;
strParent = flFileToRename.getParent();
// Generate new name for the file in a deterministic way
do
{
iIndex++;
sbBuffer.delete(0, sbBuffer.length());
if (strParent != null)
{
sbBuffer.append(strParent);
sbBuffer.append(File.separatorChar);
}
sbBuffer.append(strPrefix);
sbBuffer.append("_");
sbBuffer.append(iIndex);
sbBuffer.append("_");
sbBuffer.append(flFileToRename.getName());
flTemp = new File(sbBuffer.toString());
}
while (flTemp.exists());
// Now we should have unique name
if (!flFileToRename.renameTo(flTemp))
{
throw new IOException("Cannot rename " + flFileToRename.getAbsolutePath()
+ " to " + flTemp.getAbsolutePath());
}
}
/**
* Delete all files and directories in directory but do not delete the
* directory itself.
*
* @param strDir - string that specifies directory to delete
* @return boolean - sucess flag
*/
public static boolean deleteDirectoryContent(
String strDir
)
{
return ((strDir != null) && (strDir.length() > 0))
? deleteDirectoryContent(new File(strDir)) : false;
}
/**
* Delete all files and directories in directory but do not delete the
* directory itself.
*
* @param fDir - directory to delete
* @return boolean - sucess flag
*/
public static boolean deleteDirectoryContent(
File fDir
)
{
boolean bRetval = false;
if (fDir != null && fDir.isDirectory())
{
File[] files = fDir.listFiles();
if (files != null)
{
bRetval = true;
boolean dirDeleted;
for (int index = 0; index < files.length; index++)
{
if (files[index].isDirectory())
{
// TODO: Performance: Implement this as a queue where you add to
// the end and take from the beginning, it will be more efficient
// than the recursion
dirDeleted = deleteDirectoryContent(files[index]);
if (dirDeleted)
{
bRetval = bRetval && files[index].delete();
}
else
{
bRetval = false;
}
}
else
{
bRetval = bRetval && files[index].delete();
}
}
}
}
return bRetval;
}
/**
* Deletes all files and subdirectories under the specified directory including
* the specified directory
*
* @param strDir - string that specifies directory to be deleted
* @return boolean - true if directory was successfully deleted
*/
public static boolean deleteDir(
String strDir
)
{
return ((strDir != null) && (strDir.length() > 0))
? deleteDir(new File(strDir)) : false;
}
/**
* Deletes all files and subdirectories under the specified directory including
* the specified directory
*
* @param fDir - directory to be deleted
* @return boolean - true if directory was successfully deleted
*/
public static boolean deleteDir(
File fDir
)
{
boolean bRetval = false;
if (fDir != null && fDir.exists())
{
bRetval = deleteDirectoryContent(fDir);
if (bRetval)
{
bRetval = bRetval && fDir.delete();
}
}
return bRetval;
}
/**
* Compare binary files. Both files must be files (not directories) and exist.
*
* @param first - first file
* @param second - second file
* @return boolean - true if files are binery equal
* @throws IOException - error in function
*/
public boolean isFileBinaryEqual(
File first,
File second
) throws IOException
{
// TODO: Test: Missing test
boolean retval = false;
if ((first.exists()) && (second.exists())
&& (first.isFile()) && (second.isFile()))
{
if (first.getCanonicalPath().equals(second.getCanonicalPath()))
{
retval = true;
}
else
{
FileInputStream firstInput = null;
FileInputStream secondInput = null;
BufferedInputStream bufFirstInput = null;
BufferedInputStream bufSecondInput = null;
try
{
firstInput = new FileInputStream(first);
secondInput = new FileInputStream(second);
bufFirstInput = new BufferedInputStream(firstInput, BUFFER_SIZE);
bufSecondInput = new BufferedInputStream(secondInput, BUFFER_SIZE);
int firstByte;
int secondByte;
while (true)
{
firstByte = bufFirstInput.read();
secondByte = bufSecondInput.read();
if (firstByte != secondByte)
{
break;
}
if ((firstByte < 0) && (secondByte < 0))
{
retval = true;
break;
}
}
}
finally
{
try
{
if (bufFirstInput != null)
{
bufFirstInput.close();
}
}
finally
{
if (bufSecondInput != null)
{
bufSecondInput.close();
}
}
}
}
}
return retval;
}
/**
* Get path which represents temporary directory. It is guarantee that it
* ends with \ (or /).
*
* @return String
*/
public static String getTemporaryDirectory(
)
{
return s_strTempDirectory;
}
/**
* Copy any input stream to output file. Once the data will be copied
* the stream will be closed.
*
* @param input - InputStream to copy from
* @param output - File to copy to
* @throws IOException - error in function
* @throws OSSMultiException - double error in function
*/
public static void copyStreamToFile(
InputStream input,
File output
) throws IOException
{
FileOutputStream foutOutput = null;
// open input file as stream safe - it can throw some IOException
try
{
foutOutput = new FileOutputStream(output);
}
catch (IOException ioExec)
{
if (foutOutput != null)
{
try
{
foutOutput.close();
}
catch (IOException ioExec2)
{
}
}
throw ioExec;
}
// all streams including os are closed in copyStreamToStream function
// in any case
copyStreamToStream(input, foutOutput);
}
/**
* Copy any input stream to output stream. Once the data will be copied
* both streams will be closed.
*
* @param input - InputStream to copy from
* @param output - OutputStream to copy to
* @throws IOException - io error in function
* @throws OSSMultiException - double error in function
*/
public static void copyStreamToStream(
InputStream input,
OutputStream output
) throws IOException
{
InputStream is = null;
OutputStream os = null;
int ch;
try
{
if (input instanceof BufferedInputStream)
{
is = input;
}
else
{
is = new BufferedInputStream(input);
}
if (output instanceof BufferedOutputStream)
{
os = output;
}
else
{
os = new BufferedOutputStream(output);
}
while ((ch = is.read()) != -1)
{
os.write(ch);
}
os.flush();
}
finally
{
IOException exec1 = null;
IOException exec2 = null;
try
{
// because this close can throw exception we do next close in
// finally statement
if (os != null)
{
try
{
os.close();
}
catch (IOException exec)
{
exec1 = exec;
}
}
}
finally
{
if (is != null)
{
try
{
is.close();
}
catch (IOException exec)
{
exec2 = exec;
}
}
}
if ((exec1 != null) && (exec2 != null))
{
throw exec1;
}
else if (exec1 != null)
{
throw exec1;
}
else if (exec2 != null)
{
throw exec2;
}
}
}
}
Remove File Name Suffix
/*
* Copyright (C) 2001-2003 Colin Bell
* colbell@users.sourceforge.net
*
* 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
*/
import java.io.*;
import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* General purpose utilities functions.
*
* @author
*/
public class Utilities
{
/**
* Remove the suffix from the passed file name.
*
* @param fileName File name to remove suffix from.
*
* @return <TT>fileName</TT> without a suffix.
*
* @throws IllegalArgumentException if <TT>null</TT> file name passed.
*/
public static String removeFileNameSuffix(String fileName)
{
if (fileName == null)
{
throw new IllegalArgumentException("file name == null");
}
int pos = fileName.lastIndexOf(".");
if (pos > 0 && pos < fileName.length() - 1)
{
return fileName.substring(0, pos);
}
return fileName;
}
}
Rename To Temporary Name
/**
* Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
*
* Project: OpenSubsystems
*
* $Id: FileUtils.java,v 1.12 2007/02/01 07:18:32 bastafidli Exp $
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
/**
* Collection of methods to make work with files easier.
*
* @version $Id: FileUtils.java,v 1.12 2007/02/01 07:18:32 bastafidli Exp $
* @author Miro Halas
* @code.reviewer Miro Halas
* @code.reviewed 1.7 2006/05/21 03:45:37 bastafidli
*/
public class FileUtils
{
// Configuration settings ///////////////////////////////////////////////////
/**
* Default 10 digit file storage distribution array. This means that if I
* want to name file as 10 digit number e.g. number 123 as 0000000123 or
* number 123456789 as 01234567890. Then the path constructed from number
* 1234567890 using distribution 2/2/2/4 would be 12/34/56/0123456789
*/
public static final int[] DEFAULT_STRORAGE_TREE_DISTRIBUTION = {2, 2, 2, 4};
/**
* How big buffer to use to process files.
*/
public static final int BUFFER_SIZE = 65536;
// Cached values ////////////////////////////////////////////////////////////
/**
* Temporary directory to use. It is guarantee that it ends with \ (or /)
*/
protected static String s_strTempDirectory;
// Constructors /////////////////////////////////////////////////////////////
/**
* Move file to a new location. If the destination is on different volume,
* this file will be copied and then original file will be deleted.
* If the destination already exists, this method renames it with different
* name and leaves it in that directory and moves the new file along side
* the renamed one.
*
* @param flCurrent - file to move
* @param flDestination - destination file
* @throws IOException - error message
* @throws OSSException - error message
*/
public static void moveFile(
File flCurrent,
File flDestination
) throws IOException
{
// Make sure that the source exist, it might be already moved from
// a directory and we just don"t know about it
if (flCurrent.exists())
{
// Next check if the destination file exists
if (flDestination.exists())
{
// If the destination exists, that means something went wrong
// Rename the destination file under temporaty name and try to
// move the new file instead of it
renameToTemporaryName(flDestination, "old");
}
// Make sure the directory exists and if not create it
File flFolder;
flFolder = flDestination.getParentFile();
if ((flFolder != null) && (!flFolder.exists()))
{
if (!flFolder.mkdirs())
{
// Do not throw the exception if the directory already exists
// because it was created meanwhile for example by a different
// thread
if (!flFolder.exists())
{
throw new IOException("Cannot create directory " + flFolder);
}
}
}
// Now everything should exist so try to rename the file first
// After testing, this renames files even between volumes C to H
// so we don"t have to do anything else on Windows but we still
// have to handle erro on Unix
if (!flCurrent.renameTo(flDestination))
{
// Try to copy and delete since the rename doesn"t work on Solaris
// between file systems
copyFile(flCurrent, flDestination);
// Now delete the file
if (!flCurrent.delete())
{
// Delete the destination file first since we haven"t really moved
// the file
flDestination.delete();
throw new IOException("Cannot delete already copied file " + flCurrent);
}
}
}
}
/**
* Copy the current file to the destination file.
*
* @param flCurrent - source file
* @param flDestination - destination file
* @throws IOException - error message
* @throws OSSException - error message
*/
public static void copyFile(
File flCurrent,
File flDestination
) throws IOException
{
// Make sure the directory exists and if not create it
File flFolder;
flFolder = flDestination.getParentFile();
if ((flFolder != null) && (!flFolder.exists()))
{
if (!flFolder.mkdirs())
{
// Do not throw the exception if the directory already exists
// because it was created meanwhile for example by a different
// thread
if (!flFolder.exists())
{
throw new IOException("Cannot create directory " + flFolder);
}
}
}
// FileChannel srcChannel = null;
// FileChannel dstChannel = null;
FileInputStream finInput = null;
//MHALAS: This code is not working reliably on Solaris 8 with 1.4.1_01
// Getting exceptions from native code
/*
// Create channel on the source
srcChannel = new FileInputStream(flCurrent).getChannel();
// Create channel on the destination
dstChannel = new FileOutputStream(flDestination).getChannel();
// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
Don"t forget to close the channels if you enable this code again
*/
try
{
finInput = new FileInputStream(flCurrent);
}
catch (IOException ioExec)
{
if (finInput != null)
{
try
{
finInput.close();
}
catch (Throwable thr)
{
}
}
throw ioExec;
}
FileUtils.copyStreamToFile(finInput, flDestination);
}
/**
* Rename the file to temporaty name with given prefix
*
* @param flFileToRename - file to rename
* @param strPrefix - prefix to use
* @throws IOException - error message
*/
public static void renameToTemporaryName(
File flFileToRename,
String strPrefix
) throws IOException
{
assert strPrefix != null : "Prefix cannot be null.";
String strParent;
StringBuffer sbBuffer = new StringBuffer();
File flTemp;
int iIndex = 0;
strParent = flFileToRename.getParent();
// Generate new name for the file in a deterministic way
do
{
iIndex++;
sbBuffer.delete(0, sbBuffer.length());
if (strParent != null)
{
sbBuffer.append(strParent);
sbBuffer.append(File.separatorChar);
}
sbBuffer.append(strPrefix);
sbBuffer.append("_");
sbBuffer.append(iIndex);
sbBuffer.append("_");
sbBuffer.append(flFileToRename.getName());
flTemp = new File(sbBuffer.toString());
}
while (flTemp.exists());
// Now we should have unique name
if (!flFileToRename.renameTo(flTemp))
{
throw new IOException("Cannot rename " + flFileToRename.getAbsolutePath()
+ " to " + flTemp.getAbsolutePath());
}
}
/**
* Delete all files and directories in directory but do not delete the
* directory itself.
*
* @param strDir - string that specifies directory to delete
* @return boolean - sucess flag
*/
public static boolean deleteDirectoryContent(
String strDir
)
{
return ((strDir != null) && (strDir.length() > 0))
? deleteDirectoryContent(new File(strDir)) : false;
}
/**
* Delete all files and directories in directory but do not delete the
* directory itself.
*
* @param fDir - directory to delete
* @return boolean - sucess flag
*/
public static boolean deleteDirectoryContent(
File fDir
)
{
boolean bRetval = false;
if (fDir != null && fDir.isDirectory())
{
File[] files = fDir.listFiles();
if (files != null)
{
bRetval = true;
boolean dirDeleted;
for (int index = 0; index < files.length; index++)
{
if (files[index].isDirectory())
{
// TODO: Performance: Implement this as a queue where you add to
// the end and take from the beginning, it will be more efficient
// than the recursion
dirDeleted = deleteDirectoryContent(files[index]);
if (dirDeleted)
{
bRetval = bRetval && files[index].delete();
}
else
{
bRetval = false;
}
}
else
{
bRetval = bRetval && files[index].delete();
}
}
}
}
return bRetval;
}
/**
* Deletes all files and subdirectories under the specified directory including
* the specified directory
*
* @param strDir - string that specifies directory to be deleted
* @return boolean - true if directory was successfully deleted
*/
public static boolean deleteDir(
String strDir
)
{
return ((strDir != null) && (strDir.length() > 0))
? deleteDir(new File(strDir)) : false;
}
/**
* Deletes all files and subdirectories under the specified directory including
* the specified directory
*
* @param fDir - directory to be deleted
* @return boolean - true if directory was successfully deleted
*/
public static boolean deleteDir(
File fDir
)
{
boolean bRetval = false;
if (fDir != null && fDir.exists())
{
bRetval = deleteDirectoryContent(fDir);
if (bRetval)
{
bRetval = bRetval && fDir.delete();
}
}
return bRetval;
}
/**
* Compare binary files. Both files must be files (not directories) and exist.
*
* @param first - first file
* @param second - second file
* @return boolean - true if files are binery equal
* @throws IOException - error in function
*/
public boolean isFileBinaryEqual(
File first,
File second
) throws IOException
{
// TODO: Test: Missing test
boolean retval = false;
if ((first.exists()) && (second.exists())
&& (first.isFile()) && (second.isFile()))
{
if (first.getCanonicalPath().equals(second.getCanonicalPath()))
{
retval = true;
}
else
{
FileInputStream firstInput = null;
FileInputStream secondInput = null;
BufferedInputStream bufFirstInput = null;
BufferedInputStream bufSecondInput = null;
try
{
firstInput = new FileInputStream(first);
secondInput = new FileInputStream(second);
bufFirstInput = new BufferedInputStream(firstInput, BUFFER_SIZE);
bufSecondInput = new BufferedInputStream(secondInput, BUFFER_SIZE);
int firstByte;
int secondByte;
while (true)
{
firstByte = bufFirstInput.read();
secondByte = bufSecondInput.read();
if (firstByte != secondByte)
{
break;
}
if ((firstByte < 0) && (secondByte < 0))
{
retval = true;
break;
}
}
}
finally
{
try
{
if (bufFirstInput != null)
{
bufFirstInput.close();
}
}
finally
{
if (bufSecondInput != null)
{
bufSecondInput.close();
}
}
}
}
}
return retval;
}
/**
* Get path which represents temporary directory. It is guarantee that it
* ends with \ (or /).
*
* @return String
*/
public static String getTemporaryDirectory(
)
{
return s_strTempDirectory;
}
/**
* Copy any input stream to output file. Once the data will be copied
* the stream will be closed.
*
* @param input - InputStream to copy from
* @param output - File to copy to
* @throws IOException - error in function
* @throws OSSMultiException - double error in function
*/
public static void copyStreamToFile(
InputStream input,
File output
) throws IOException
{
FileOutputStream foutOutput = null;
// open input file as stream safe - it can throw some IOException
try
{
foutOutput = new FileOutputStream(output);
}
catch (IOException ioExec)
{
if (foutOutput != null)
{
try
{
foutOutput.close();
}
catch (IOException ioExec2)
{
}
}
throw ioExec;
}
// all streams including os are closed in copyStreamToStream function
// in any case
copyStreamToStream(input, foutOutput);
}
/**
* Copy any input stream to output stream. Once the data will be copied
* both streams will be closed.
*
* @param input - InputStream to copy from
* @param output - OutputStream to copy to
* @throws IOException - io error in function
* @throws OSSMultiException - double error in function
*/
public static void copyStreamToStream(
InputStream input,
OutputStream output
) throws IOException
{
InputStream is = null;
OutputStream os = null;
int ch;
try
{
if (input instanceof BufferedInputStream)
{
is = input;
}
else
{
is = new BufferedInputStream(input);
}
if (output instanceof BufferedOutputStream)
{
os = output;
}
else
{
os = new BufferedOutputStream(output);
}
while ((ch = is.read()) != -1)
{
os.write(ch);
}
os.flush();
}
finally
{
IOException exec1 = null;
IOException exec2 = null;
try
{
// because this close can throw exception we do next close in
// finally statement
if (os != null)
{
try
{
os.close();
}
catch (IOException exec)
{
exec1 = exec;
}
}
}
finally
{
if (is != null)
{
try
{
is.close();
}
catch (IOException exec)
{
exec2 = exec;
}
}
}
if ((exec1 != null) && (exec2 != null))
{
throw exec1;
}
else if (exec1 != null)
{
throw exec1;
}
else if (exec2 != null)
{
throw exec2;
}
}
}
}
Return readable file size with selected value measure
/**
* Methods for files and folders treatment.
*
* @author Cyril JOUI
*/
public final class FileUtil {
/**
* @param fileSize
* file size to convert and format to string.
* @return return readable file size with selected value measure
*/
public static String getReadableFileSize(final long fileSize) {
double l = fileSize * 1D;
String s = "";
if (l < 1000) {
s = fileSize + " B";
} else {
l = l / 1024D;
if (l < 1000) {
s = l + " KB";
} else {
l = l / 1024D;
if (l < 1000) {
s = l + " MB";
} else {
l = l / 1024D;
s = l + " GB";
}
}
}
return (s.length() - s.indexOf(".") <= 3 ? s : s.substring(0, s.indexOf(".") + 3))
+ s.substring(s.indexOf(" "), s.length());
}
}
Strip File Extension
/**
*
* The ObjectStyle Group Software License, version 1.1
* ObjectStyle Group - http://objectstyle.org/
*
* Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
* of the software. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if any,
* must include the following acknowlegement:
* "This product includes software developed by independent contributors
* and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
* or promote products derived from this software without prior written
* permission. For written permission, email
* "andrus at objectstyle dot org".
*
* 5. Products derived from this software may not be called "ObjectStyle"
* or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
* names without prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many
* individuals and hosted on ObjectStyle Group web site. For more
* information on the ObjectStyle Group, please see
* <http://objectstyle.org/>.
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ruparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Contains various unorganized static utility methods used across Cayenne.
*
* @author Andrei Adamchik
*/
public class Util {
/**
* Strips extension from the file name.
*/
public static String stripFileExtension(String fileName) {
int dotInd = fileName.lastIndexOf(".");
// if dot is in the first position,
// we are dealing with a hidden file rather than an extension
return (dotInd > 0) ? fileName.substring(0, dotInd) : fileName;
}
}
Utility class for synchronizing files/directories
//$Id: FileHelper.java 15522 2008-11-05 20:06:43Z hardy.ferentschik $
//Revised from hibernate search util
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Utility class for synchronizing files/directories.
*
* @author Emmanuel Bernard
* @author Sanne Grinovero
* @author Hardy Ferentschik
*/
public abstract class FileHelper {
private static final int FAT_PRECISION = 2000;
public static final long DEFAULT_COPY_BUFFER_SIZE = 16 * 1024 * 1024; // 16 MB
public static boolean areInSync(File source, File destination) throws IOException {
if ( source.isDirectory() ) {
if ( !destination.exists() ) {
return false;
}
else if ( !destination.isDirectory() ) {
throw new IOException(
"Source and Destination not of the same type:"
+ source.getCanonicalPath() + " , " + destination.getCanonicalPath()
);
}
String[] sources = source.list();
Set<String> srcNames = new HashSet<String>( Arrays.asList( sources ) );
String[] dests = destination.list();
// check for files in destination and not in source
for ( String fileName : dests ) {
if ( !srcNames.contains( fileName ) ) {
return false;
}
}
boolean inSync = true;
for ( String fileName : sources ) {
File srcFile = new File( source, fileName );
File destFile = new File( destination, fileName );
if ( !areInSync( srcFile, destFile ) ) {
inSync = false;
break;
}
}
return inSync;
}
else {
if ( destination.exists() && destination.isFile() ) {
long sts = source.lastModified() / FAT_PRECISION;
long dts = destination.lastModified() / FAT_PRECISION;
return sts == dts;
}
else {
return false;
}
}
}
public static void synchronize(File source, File destination, boolean smart) throws IOException {
synchronize( source, destination, smart, DEFAULT_COPY_BUFFER_SIZE );
}
public static void synchronize(File source, File destination, boolean smart, long chunkSize) throws IOException {
if ( chunkSize <= 0 ) {
System.out.println("Chunk size must be positive: using default value." );
chunkSize = DEFAULT_COPY_BUFFER_SIZE;
}
if ( source.isDirectory() ) {
if ( !destination.exists() ) {
if ( !destination.mkdirs() ) {
throw new IOException( "Could not create path " + destination );
}
}
else if ( !destination.isDirectory() ) {
throw new IOException(
"Source and Destination not of the same type:"
+ source.getCanonicalPath() + " , " + destination.getCanonicalPath()
);
}
String[] sources = source.list();
Set<String> srcNames = new HashSet<String>( Arrays.asList( sources ) );
String[] dests = destination.list();
//delete files not present in source
for ( String fileName : dests ) {
if ( !srcNames.contains( fileName ) ) {
delete( new File( destination, fileName ) );
}
}
//copy each file from source
for ( String fileName : sources ) {
File srcFile = new File( source, fileName );
File destFile = new File( destination, fileName );
synchronize( srcFile, destFile, smart, chunkSize );
}
}
else {
if ( destination.exists() && destination.isDirectory() ) {
delete( destination );
}
if ( destination.exists() ) {
long sts = source.lastModified() / FAT_PRECISION;
long dts = destination.lastModified() / FAT_PRECISION;
//do not copy if smart and same timestamp and same length
if ( !smart || sts == 0 || sts != dts || source.length() != destination.length() ) {
copyFile( source, destination, chunkSize );
}
}
else {
copyFile( source, destination, chunkSize );
}
}
}
private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException {
FileInputStream is = null;
FileOutputStream os = null;
try {
is = new FileInputStream( srcFile );
FileChannel iChannel = is.getChannel();
os = new FileOutputStream( destFile, false );
FileChannel oChannel = os.getChannel();
long doneBytes = 0L;
long todoBytes = srcFile.length();
while ( todoBytes != 0L ) {
long iterationBytes = Math.min( todoBytes, chunkSize );
long transferredLength = oChannel.transferFrom( iChannel, doneBytes, iterationBytes );
if ( iterationBytes != transferredLength ) {
throw new IOException(
"Error during file transfer: expected "
+ iterationBytes + " bytes, only " + transferredLength + " bytes copied."
);
}
doneBytes += transferredLength;
todoBytes -= transferredLength;
}
}
finally {
if ( is != null ) {
is.close();
}
if ( os != null ) {
os.close();
}
}
boolean successTimestampOp = destFile.setLastModified( srcFile.lastModified() );
if ( !successTimestampOp ) {
System.out.println("Could not change timestamp for {}. Index synchronization may be slow. " + destFile );
}
}
public static void delete(File file) {
if ( file.isDirectory() ) {
for ( File subFile : file.listFiles() ) {
delete( subFile );
}
}
if ( file.exists() ) {
if ( !file.delete() ) {
System.out.println( "Could not delete {}" + file );
}
}
}
}