Skip to content

Commit

Permalink
Mostly set default encoding for File methods to use UTF-8 or chosen d…
Browse files Browse the repository at this point in the history
…efault. Also check returns from File methods.
  • Loading branch information
rkiddy committed Sep 13, 2012
1 parent c335dc0 commit 4f9d824
Show file tree
Hide file tree
Showing 2 changed files with 554 additions and 188 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Calendar;
Expand All @@ -53,7 +53,10 @@
import er.extensions.foundation.ERXRuntimeUtilities.TimeoutException;

/**
* Collection of handy {java.io.File} utilities.
* Collection of handy {java.io.File} utilities.
*
* By default, will use UTF-8 for the character set, though one can set the static ivar to
* override this choice.
*/
public class ERXFileUtilities {

Expand All @@ -64,6 +67,26 @@ public class ERXFileUtilities {
/** logging support */
public static final Logger log = Logger.getLogger(ERXFileUtilities.class);

private static Charset charset = null;

static { setDefaultCharset("UTF-8"); }

// ===========================================================================
// Static Methods
// ---------------------------------------------------------------------------

public static Charset charset() { return charset; }

public static void setDefaultCharset(String name) {
Charset original = charset;
try {
charset = Charset.forName(name);
} catch (Exception e) {
log.error("Unable to set default charset to \""+name+"\"");
charset = original;
}
}

// ===========================================================================
// Class Methods
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -273,7 +296,7 @@ public static void writeInputStreamToFile(File f, InputStream is) throws IOExcep
* @param stream
* to pull data from
* @return the temp file that was created
* @throws IOException if things go wrong
* @throws IOException if things go wrong
*/
public static File writeInputStreamToTempFile(InputStream stream) throws IOException {
return ERXFileUtilities.writeInputStreamToTempFile(stream, "_Wonder", ".tmp");
Expand All @@ -287,34 +310,39 @@ public static File writeInputStreamToTempFile(InputStream stream) throws IOExcep
* @param prefix the filename prefix of the temp file
* @param suffix the filename suffix of the temp file
* @return the temp file that was created
* @throws IOException if things go wrong
* @throws IOException if things go wrong
*/
public static File writeInputStreamToTempFile(InputStream stream, String prefix, String suffix) throws IOException {
File tempFile;
try {
tempFile = File.createTempFile(prefix, suffix);
try {
ERXFileUtilities.writeInputStreamToFile(stream, tempFile);
}
catch (RuntimeException e) {
tempFile.delete();
throw e;
}
catch (IOException e) {
tempFile.delete();
throw e;
}
}
catch (RuntimeException e) {
stream.close();
throw e;
}
catch (IOException e) {
stream.close();
throw e;
}
return tempFile;
}
File tempFile;
try {
tempFile = File.createTempFile(prefix, suffix);
try {
ERXFileUtilities.writeInputStreamToFile(stream, tempFile);
}
catch (RuntimeException e) {
if (! tempFile.delete())
log.error("RuntimeException occured, but cannot delete tempFile \""+tempFile.getPath()+"\"");
throw e;
}
catch (IOException e) {
if (! tempFile.delete())
log.error("IOException occured, but cannot delete tempFile \""+tempFile.getPath()+"\"");
throw e;
}
}
catch (RuntimeException e) {
stream.close();
throw e;
}
catch (IOException e) {
stream.close();
throw e;
}
finally {
stream.close();
}
return tempFile;
}

/**
* Writes the contents of an InputStream to a specified file.
Expand All @@ -328,7 +356,8 @@ public static void writeInputStreamToFile(InputStream stream, File file) throws
if (file == null) throw new IllegalArgumentException("Attempting to write to a null file!");
File parent = file.getParentFile();
if(parent != null && !parent.exists()) {
parent.mkdirs();
if (! parent.mkdirs())
throw new RuntimeException("Cannot create parent directory for file");
}
out = new FileOutputStream(file);
}
Expand Down Expand Up @@ -398,7 +427,7 @@ public static void stringToGZippedFile(String s, File f) throws IOException {
if (s == null) throw new NullPointerException("string argument cannot be null");
if (f == null) throw new NullPointerException("file argument cannot be null");

byte[] bytes = s.getBytes();
byte[] bytes = s.getBytes(charset());
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
writeInputStreamToGZippedFile(bais, f);
}
Expand Down Expand Up @@ -496,15 +525,15 @@ public static void remoteCopyFile(String srcHost, String srcPath, File dstFile)
}

/**
* Returns a string from the gzipped file using the default
* encoding.
* @param f file to read
* @return string representation of that file.
* Returns a string from the gzipped file using the default
* encoding.
* @param f file to read
* @return string representation of that file.
* @throws IOException if things go wrong
*/
public static String stringFromGZippedFile(File f) throws IOException {
return new String(bytesFromGZippedFile(f));
}
*/
public static String stringFromGZippedFile(File f) throws IOException {
return new String(bytesFromGZippedFile(f), charset());
}

/**
* Returns a string from the file using the default
Expand All @@ -514,7 +543,7 @@ public static String stringFromGZippedFile(File f) throws IOException {
* @throws IOException if things go wrong
*/
public static String stringFromFile(File f) throws IOException {
return new String(bytesFromFile(f));
return new String(bytesFromFile(f), charset());
}

/**
Expand All @@ -527,7 +556,7 @@ public static String stringFromFile(File f) throws IOException {
*/
public static String stringFromFile(File f, String encoding) throws IOException {
if (encoding == null) {
return new String(bytesFromFile(f));
return new String(bytesFromFile(f), charset());
}
return new String(bytesFromFile(f), encoding);
}
Expand Down Expand Up @@ -651,7 +680,7 @@ public static URL URLFromFile(File file) {
if(file != null) {
try {
url = URLFromPath(file.getCanonicalPath());
} catch(IOException ex) {
} catch (IOException ex) {
throw new NSForwardException(ex);
}
}
Expand All @@ -668,7 +697,7 @@ public static URL URLFromPath(String fileName) {
if(fileName != null) {
try {
url = new URL("file://" + fileName);
} catch(MalformedURLException ex) {
} catch (java.net.MalformedURLException ex) {
throw new NSForwardException(ex);
}
}
Expand Down Expand Up @@ -818,7 +847,7 @@ public static void deleteFilesInDirectory(File directory, boolean recurseIntoDir
*/
public static void deleteFilesInDirectory(File directory, FileFilter filter, boolean recurseIntoDirectories, boolean removeDirectories) {
if (!directory.exists())
throw new RuntimeException("Attempting to delete files from a non-existant directory: " + directory);
throw new RuntimeException("Attempting to delete files from a non-existent directory: " + directory);
if (!directory.isDirectory())
throw new RuntimeException("Attmepting to delete files from a file that is not a directory: " + directory);
File files[] = filter != null ? directory.listFiles(filter) : directory.listFiles() ;
Expand All @@ -830,7 +859,8 @@ public static void deleteFilesInDirectory(File directory, FileFilter filter, boo
}
if (aFile.isFile() || (aFile.isDirectory() && removeDirectories
&& (aFile.listFiles() == null || aFile.listFiles().length == 0))) {
aFile.delete();
if (! aFile.delete())
throw new RuntimeException("Directory \""+directory+"\" not successfully deleted.");
}
}
}
Expand Down Expand Up @@ -925,7 +955,7 @@ public static void linkFiles(File source, File destination,
catch (InterruptedException e) {}
}
if (task.exitValue() != 0) {
BufferedReader err = new BufferedReader(new InputStreamReader(task.getErrorStream()));
BufferedReader err = new BufferedReader(new InputStreamReader(task.getErrorStream(), charset()));
throw new IOException("Unable to create link: " + err.readLine());
}
} finally {
Expand Down Expand Up @@ -957,7 +987,7 @@ public static void copyFilesFromDirectory(File srcDirectory,
* @param dstDirectory destination directory
* @param deleteOriginals tells if the original files, the file is deleted even if appuser has no write
* rights. This is compareable to a <code>rm -f filename</code> instead of <code>rm filename</code>
* @param replaceExistingFiles <code>true</code> if the destination should be overwritten if it already exists
* @param replaceExistingFiles <code>true</code> if the destination should be overwritten if it already exists
* @param recursiveCopy specifies if directories should be recursively copied
* @param filter which restricts the files to be copied
* @throws IOException if things go wrong
Expand All @@ -967,14 +997,16 @@ public static void copyFilesFromDirectory(File srcDirectory,
boolean deleteOriginals,
boolean replaceExistingFiles,
boolean recursiveCopy,
FileFilter filter)
throws IOException {
FileFilter filter) throws IOException {

if (!srcDirectory.exists() || !dstDirectory.exists())
throw new RuntimeException("Both the src and dst directories must exist! Src: " + srcDirectory
+ " Dst: " + dstDirectory);

File srcFiles[] = filter!=null ?
srcDirectory.listFiles(filter) :
srcDirectory.listFiles();

if (srcFiles != null && srcFiles.length > 0) {

for (int i = 0; i < srcFiles.length; i++) {
Expand All @@ -985,8 +1017,10 @@ public static void copyFilesFromDirectory(File srcDirectory,
if (deleteOriginals) {
renameTo(srcFile, dstFile);
} else {
dstFile.mkdirs();
copyFilesFromDirectory(srcFile, dstFile, deleteOriginals, replaceExistingFiles, recursiveCopy, filter);
if (dstFile.mkdirs())
copyFilesFromDirectory(srcFile, dstFile, deleteOriginals, replaceExistingFiles, recursiveCopy, filter);
else
log.error("Error creating directories for destination \""+dstDirectory.getPath()+"\"");
}
} else if (!srcFile.isDirectory()) {
if (replaceExistingFiles || ! dstFile.exists()) {
Expand Down Expand Up @@ -1022,7 +1056,7 @@ public static void copyFileToFile(File srcFile, File dstFile, boolean deleteOrig
if (!copied) {
Throwable thrownException = null;
File parent = dstFile.getParentFile();
if (!parent.exists() && !parent.mkdirs()) {
if (! parent.exists() && ! parent.mkdirs()) {
throw new IOException("Failed to create the directory " + parent + ".");
}

Expand Down Expand Up @@ -1054,21 +1088,18 @@ public static void copyFileToFile(File srcFile, File dstFile, boolean deleteOrig
finally {
out.close();
}
}
catch (Throwable t) {
} catch (Throwable t) {
if (thrownException == null) {
thrownException = t;
}
}
finally {
} finally {
srcChannel.close();
}
} catch (Throwable t) {
if (thrownException == null) {
thrownException = t;
}
}
finally {
} finally {
try {
in.close();
}
Expand Down Expand Up @@ -1108,17 +1139,20 @@ else if (thrownException instanceof Error) {
* @exception IOException if something goes wrong
*/
public static final File createTempDir() throws IOException {
File f = File.createTempFile("WonderTempDir", "");
File f = createTempDir("WonderTempDir", "");

if (f.delete() || f.delete())
log.debug("Could not delete temporary directory: \""+f.getPath()+"\"");

f.delete();
f.delete();
f.mkdirs();
if (! f.mkdirs())
log.error("Could not create temporary directory: \""+f.getPath()+"\"");

return f;
}

/**
* Creates a temporary directory.
*
* @param prefix prefix to use for the filename
* @param suffix suffix to use for the filename
*
Expand All @@ -1129,9 +1163,11 @@ public static final File createTempDir() throws IOException {
public static final File createTempDir(String prefix, String suffix) throws IOException {
File f = File.createTempFile(prefix, suffix);

f.delete();
f.delete();
f.mkdirs();
if (f.delete() || f.delete())
log.debug("Could not delete temporary directory: \""+f.getPath()+"\"");

if (! f.mkdirs())
log.error("Could not create temporary directory: \""+f.getPath()+"\"");

return f;
}
Expand Down Expand Up @@ -1209,6 +1245,7 @@ public static String replaceFileExtension(String path, String newExtension) {
* @exception IOException if something goes wrong
*/
public static File unzipFile(File f, File destination) throws IOException {

if (!f.exists()) {
throw new FileNotFoundException("file "+f+" does not exist");
}
Expand All @@ -1217,7 +1254,8 @@ public static File unzipFile(File f, File destination) throws IOException {
if (destination != null) {
absolutePath = destination.getAbsolutePath();
if (!destination.exists()) {
destination.mkdirs();
if (! destination.mkdirs())
throw new RuntimeException("Cannot create destination directory: \""+destination.getPath()+"\"");
} else if (!destination.isDirectory()) {
absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
}
Expand All @@ -1238,8 +1276,10 @@ public static File unzipFile(File f, File destination) throws IOException {
if (dir.endsWith(".zip")) {
dir = dir.substring(0, dir.length() - 4);
}
new File(dir).mkdirs();
absolutePath = dir + File.separator;
if (new File(dir).mkdirs())
absolutePath = dir + File.separator;
else
throw new IOException("Cannot create directory: \""+dir+"\"");
}
} else {
return null;
Expand All @@ -1250,7 +1290,8 @@ public static File unzipFile(File f, File destination) throws IOException {
String name = ze.getName();
if (ze.isDirectory()) {
File d = new File(absolutePath + name);
d.mkdirs();
if (! d.mkdirs())
throw new IOException("Cannot create directory: \""+d.getPath()+"\"");
if (log.isDebugEnabled()) {
log.debug("created directory "+d.getAbsolutePath());
}
Expand All @@ -1260,6 +1301,7 @@ public static File unzipFile(File f, File destination) throws IOException {
if (log.isDebugEnabled()) {
log.debug("unzipped file "+ze.getName()+" into "+(absolutePath + name));
}
is.close();
}
}

Expand Down
Loading

0 comments on commit 4f9d824

Please sign in to comment.