package com.philmcrew.utility; /* * * Lifted and greatly extended from: * * Java I/O - Elliotte Rusty Harold * An Efficient Stream Copier - page 43 * * @author Mitchell J. Friedman * */ import java.io.*; import java.net.Socket; import java.net.URLConnection; import java.net.URL; import java.util.Properties; /** * StreamCopier is a utility class designed to make certain Stream functions easier. * * It was based on a StreamCopier class included in * Java I/O by Elliotte Rusty Harold * An Efficient Stream copier - page 43 * * And greatly extended. Mostly I got tired for seeing the same code in many * places, written badly, often forgetting to close the Streams. * * Part of the reason the Streams aren't closed is the ugliness of having to put * the close in a try/catch block - solved here by static close utility methods. * * This class could/should be customized by changing the log methods. It originally * called log4j directly. * * Enjoy. * mjf - http://www.mindspring.com/~mjfriedman/mjf.html */ public class StreamCopier { protected int copyBufSize = 256; public StreamCopier() { } protected static void logTrace(String logMessage) { System.out.println(logMessage); } protected static String logError(Throwable t, String logMessage) { StringBuffer buf = new StringBuffer(100); buf.append("Caught Throwable "); buf.append(t.getClass().getName()); buf.append(" - "); buf.append(t); buf.append(" - in "); buf.append(logMessage); System.err.println(buf); t.printStackTrace(); return buf.toString(); } public static void close(InputStream is, String methodName) { try { if (null != is) is.close(); } catch (Exception e) { logError(e, "Closing InputStream - in " + methodName); } } public static void close(OutputStream os, String methodName) { try { if (null != os) { os.flush(); os.close(); } } catch (Exception e) { logError(e, "Closing OutputStream - in " + methodName); } } public static void close(Reader r, String methodName) { try { if (null != r) r.close(); } catch (Exception e) { logError(e, "Closing Reader - in " + methodName); } } public static void close(Writer wr, String methodName) { try { if (null != wr) { wr.flush(); wr.close(); } } catch (Exception e) { logError(e, "Closing Writer - in " + methodName); } } public static void close(Socket s, String methodName) { try { if (null != s) s.close(); } catch (Exception e) { logError(e, "Closing Socket - in " + methodName); } } public int getCopyBufSize() { return copyBufSize; } public void setCopyBufSize(int copyBufSize) { this.copyBufSize = copyBufSize; } /** * * @param in * @param out * @return Total Bytes Read * @throws java.io.IOException */ public long copy(InputStream in, OutputStream out) throws IOException { long totalBytesRead = 0; // Do not allow other threads to read from the input // or write to the output while copying is taking place synchronized (in) { synchronized (out) { byte[] buffer = new byte[getCopyBufSize()]; int bytesRead; while (true) { bytesRead = in.read(buffer); if (bytesRead == -1) break; totalBytesRead += bytesRead; out.write(buffer, 0, bytesRead); } } } out.flush(); return totalBytesRead; } /** * * @param in * @param out * @return Total Chars Read * @throws java.io.IOException */ public long copy(Reader in, Writer out) throws IOException { long totalCharsRead = 0; // Do not allow other threads to read from the input // or write to the output while copying is taking place synchronized (in) { synchronized (out) { char[] buffer = new char[getCopyBufSize()]; int charsRead; while (true) { charsRead = in.read(buffer); if (charsRead == -1) break; totalCharsRead += charsRead; out.write(buffer, 0, charsRead); } } } out.flush(); return totalCharsRead; } public long copy(Reader in, OutputStream out) throws IOException { Writer wout = new BufferedWriter(new OutputStreamWriter(out)); return copy(in, wout); } public long copy(InputStream in, Writer out) throws IOException { BufferedReader rin = new BufferedReader(new InputStreamReader(in)); return copy(rin, out); } public File createTempFile(String prefix, String suffix) throws IOException { logTrace("createTempFile p=" + prefix + ";s=" + suffix); // need to get temporary directory String tmpdir = System.getProperty("java.io.tmpdir"); File tempFile = null; if (null != tmpdir && tmpdir.length() > 0) tempFile = new File(tmpdir); return File.createTempFile(prefix, suffix, tempFile); } /** * * @param in * @return Entire contents of stream as a String * @throws java.io.IOException */ public String read(InputStream in) throws IOException { ByteArrayOutputStream baos = null; String retString = null; int inputSize = in.available(); try { baos = new ByteArrayOutputStream(inputSize); copy(in, baos); retString = baos.toString(); } finally { close(baos, "StreamCopier.read"); } return retString; } public String read(URLConnection urlConnection) throws IOException { String retString = null; InputStream inputStream = null; try { inputStream = urlConnection.getInputStream(); retString = read(inputStream); } finally { close(inputStream, "StreamCopier.read"); } return retString; } public String read(URL url) throws IOException { URLConnection urlConnection = url.openConnection(); return read(urlConnection); } /** * * @param in * @return Entire contents of reader as a String * @throws java.io.IOException */ public String read(Reader in) throws IOException { String retString = null; StringWriter sw = null; try { sw = new StringWriter(); copy(in, sw); retString = sw.toString(); } finally { close(sw, "StreamCopier.read"); } return retString; } /** * * @param in * @return Entire contents of file as a String * @throws java.io.IOException */ public String read(File in) throws IOException { String retString = null; FileInputStream fis = null; try { fis = new FileInputStream(in); retString = read(fis); } finally { close(fis, "StreamCopier.read"); } return retString; } /** * * @param fileName Name of input file * @return Entire contents of filename as a String * @throws java.io.IOException */ public String readFile(String fileName) throws IOException { FileInputStream fis = null; String retString = null; try { fis = new FileInputStream(fileName); retString = read(fis); } finally { close(fis, "readFile fn=" + fileName); } return retString; } /** * * @param newFile Name of output file * @param fileContents String to be put into output file * @throws java.io.IOException */ public void write(File newFile, String fileContents) throws IOException { FileWriter fw = null; try { String fileName = null; if (null != newFile) fileName = newFile.getAbsolutePath(); logTrace("write fn=" + fileName); newFile.delete(); newFile.createNewFile(); fw = new FileWriter(fileName); fw.write(fileContents); fw.flush(); } catch (IOException e) { logError(e, "StreamCopier.write"); throw e; } finally { close(fw, "StreamCopier.write"); } } /** * * @param fileName * @param fileContents * @return the new File created * @throws java.io.IOException */ public File writeFile(String fileName, String fileContents) throws IOException { logTrace("writeFile fn=" + fileName); File newFile = new File(fileName); write(newFile, fileContents); return newFile; } /** * Create a temp file from a string * @param fileContents * @return the absolute path to the file * @throws IOException */ public String createTempFile(String fileContents) throws IOException { File tempFile = createTempFile("_tmp_", null); logTrace("createTempFile Tmp file=" + tempFile.getAbsolutePath()); write(tempFile, fileContents); return tempFile.getAbsolutePath(); } public Properties loadProperties(InputStream is) throws IOException { Properties retProp = new Properties(); retProp.load(is); return retProp; } public Properties loadProperties(String fileName) throws FileNotFoundException, IOException { Properties retProp = null; InputStream is = null; try { is = new FileInputStream(fileName); retProp = loadProperties(is); } finally { if (null != is) close(is, "load fn=" + fileName); } return retProp; } public Properties loadProperties(File file) throws FileNotFoundException, IOException { String fileName = null; Properties retProp = null; InputStream is = null; try { fileName = file.getName(); is = new FileInputStream(file); retProp = loadProperties(is); logTrace("loadProperties load fn=" + fileName + ";s=" + retProp.size()); } finally { close(is, "load fn=" + fileName); } return retProp; } /* * 2005-04-07 Thanks to Mattias Reichel the InputStreams now get closed */ public long copyFile(String inFileName, String outFileName) throws IOException { long readCount = 0; FileInputStream fis = null; FileOutputStream fos = null; try { logTrace("copyFile in=" + inFileName + ";out=" + outFileName); fis = new FileInputStream(inFileName); fos = new FileOutputStream(outFileName); readCount = copy(fis, fos); } catch (IOException e) { logError(e, "copyFile in=" + inFileName + ";out=" + outFileName); throw e; } finally { close(fis, "StreamCopier.copyFile"); close(fos, "StreamCopier.copyFile"); } return readCount; } public boolean moveFile(String inFileName, String outFileName) throws IOException { boolean ret = false; try { logTrace("moveFile in=" + inFileName + ";out=" + outFileName); copyFile(inFileName, outFileName); ret = deleteFile(inFileName); } catch (IOException e) { logError(e, "moveFile in=" + inFileName + ";out=" + outFileName); throw e; } return ret; } public boolean deleteFile(String fileName) { File fileIn = new File(fileName); return fileIn.delete(); } }