001: package org.igfay.util;
002:
003: import java.io.BufferedInputStream;
004: import java.io.BufferedReader;
005: import java.io.File;
006: import java.io.FileInputStream;
007: import java.io.FileNotFoundException;
008: import java.io.FileOutputStream;
009: import java.io.FileReader;
010: import java.io.FileWriter;
011: import java.io.IOException;
012: import java.io.InputStream;
013: import java.io.InputStreamReader;
014: import java.io.ObjectInputStream;
015: import java.io.ObjectOutputStream;
016: import java.io.OutputStream;
017: import java.io.PrintStream;
018: import java.io.PrintWriter;
019: import java.net.URL;
020: import java.util.Iterator;
021:
022: import org.apache.log4j.Logger;
023:
024: /**
025: * Helper methods for working with File objects
026: *
027: *@author bconrad
028: *@created April 17, 2001
029: */
030: public class FileUtility {
031:
032: protected static Logger log = Logger.getLogger(FileUtility.class);
033:
034: /**
035: * Return the contents of the provided File as a String
036: * @param file
037: * @return
038: */
039: public static String contentsOfFile(File file) {
040: String s = new String();
041: char[] buff = new char[50000];
042: InputStream is;
043: InputStreamReader reader;
044: try {
045: reader = new FileReader(file);
046: int nch;
047: while ((nch = reader.read(buff, 0, buff.length)) != -1) {
048: s = s + new String(buff, 0, nch);
049: }
050: } catch (java.io.IOException ex) {
051: s = null;
052: }
053: return s;
054: }
055:
056: /**
057: * Return the contents of the provided file name as a String
058: *
059: * @param fileName
060: * @return
061: */
062: public static String contentsOfFile(String fileName) {
063: return contentsOfFile(new File(fileName));
064: }
065:
066: /**
067: *
068: */
069: public static void copy(File inFile, File outFile)
070: throws IOException {
071:
072: if (inFile.getCanonicalPath()
073: .equals(outFile.getCanonicalPath())) {
074: // inFile and outFile are the same,
075: // hence no copying is required
076: return;
077: }
078: FileInputStream fin = new FileInputStream(inFile);
079: FileOutputStream fout = new FileOutputStream(outFile);
080: copy(fin, fout);
081: }
082:
083: /**
084: *
085: */
086: public static void copy(InputStream in, OutputStream out)
087: throws IOException {
088:
089: synchronized (in) {
090: synchronized (out) {
091:
092: byte[] buffer = new byte[256];
093: try {
094: while (true) {
095: int bytesRead = in.read(buffer);
096: if (bytesRead == -1)
097: break;
098: out.write(buffer, 0, bytesRead);
099: }
100: } catch (IOException e) {
101: closeStreams(in, out);
102: throw e;
103: }
104: }
105: closeStreams(in, out);
106:
107: }
108:
109: }
110:
111: /**
112: * Close the provided input and output streams. Ignore any exception.
113: *
114: * @param inputStream
115: * @param outputStream
116: */
117: public static void closeStreams(InputStream inputStream,
118: OutputStream outputStream) {
119: try {
120: inputStream.close();
121: outputStream.close();
122: } catch (Exception e) {
123: }
124: }
125:
126: /**
127: * Ensure that the provided file exists. If it does not, create it along
128: * with any necessary directories in the path.
129: *
130: * @param file
131: * @return
132: */
133: public static boolean ensureFilePathExists(File file) {
134: File path;
135: try {
136: path = new File(file.getCanonicalPath());
137: } catch (IOException e) {
138: log.debug("IOException on file " + file);
139: return false;
140: }
141: if (!path.exists()) {
142: File parent = new File(path.getParent());
143: log.debug("path does not exist, call self with parent "
144: + parent);
145: ensurePathExists(parent);
146: }
147: return true;
148: }
149:
150: /**
151: * Ensure that the path to the provided file exists. If it does not, create it.
152: *
153: * @param file
154: * @return
155: */
156: public static boolean ensurePathExists(File file) {
157: File path;
158: try {
159: path = new File(file.getCanonicalPath());
160: } catch (IOException e) {
161: log.debug("IOException on file " + file);
162: return false;
163: }
164: if (!path.exists()) {
165: if (path.getParent() == null) {
166: log
167: .debug("Operation terminating. Unable to get parent for "
168: + path.getAbsolutePath());
169: return false;
170: }
171: File parent = new File(path.getParent());
172: ensurePathExists(parent);
173: boolean result = path.mkdir();
174: log.debug("result " + result + " mkdir for " + path);
175: return result;
176:
177: }
178: return true;
179: }
180:
181: /**
182: * Ensure that the provided file name exists. If it does not, create it along
183: * with any necessary directories in the path.
184: *
185: *
186: * @param fileString
187: * @return
188: */
189: public static boolean ensureFilePathExists(String fileString) {
190: return ensureFilePathExists(new File(fileString));
191: }
192:
193: /**
194: * Ensure that the path to the provided file name exists. If it does not, create it.
195: * @param fileString
196: * @return
197: */
198: public static boolean ensurePathExists(String fileString) {
199: return ensurePathExists(new File(fileString));
200: }
201:
202: public static PrintStream newPrintStreamOnFileNamed(File directory,
203: String name) throws IOException {
204: File file = new File(directory, name);
205: log.debug("creating file " + name + " in "
206: + directory.toString());
207: return new PrintStream(new FileOutputStream(file));
208: }
209:
210: /**
211: * Create and return a PrintWriter for the provided directory and file name.
212: * @param directory
213: * @param name
214: * @return
215: * @throws IOException
216: */
217: public static PrintWriter newPrintWriterOnFileNamed(File directory,
218: String name) throws IOException {
219: File file = new File(directory, name);
220: return new PrintWriter(new FileOutputStream(file));
221: }
222:
223: /**
224: * Convert the provided File into a BufferedInputStream.
225: * Then read the stream and return the Object that was read.
226: *
227: * @param file
228: * @return
229: * @throws IOException
230: * @throws ClassNotFoundException
231: */
232: public static Object readObjectFromBufferedFileObject(File file)
233: throws IOException, ClassNotFoundException {
234: ObjectInputStream ois;
235: Object result = null;
236: log.debug("Opening input stream...");
237: FileInputStream fis = new FileInputStream(file);
238: BufferedInputStream bis = new BufferedInputStream(fis, 4096);
239: ois = new ObjectInputStream(bis);
240: log.debug("Reading serialized object from stream...");
241: result = ois.readObject();
242: return (result);
243: }
244:
245: /**
246: * Read the provded file and return the contents as an Object.
247: *
248: *@param file java.lang.String
249: *@return java.lang.Object
250: *@exception IOException Description of Exception
251: *@exception ClassNotFoundException Description of Exception
252: */
253: public static Object readObjectFromFile(File file)
254: throws IOException, ClassNotFoundException {
255: log.debug("File " + file.toString());
256: return readObjectFromBufferedFileObject(file);
257: }
258:
259: /**
260: * Read the contents of the provided file name residing in the provided directory.
261: * Return the contents as an Object.
262: *
263: *@param directory
264: *@param name
265: *@return java.lang.Object
266: *@exception IOException
267: *@exception ClassNotFoundException
268: */
269: public static Object readObjectFromFile(File directory, String name)
270: throws IOException, ClassNotFoundException {
271: File file;
272: file = new File(directory, name);
273: log.debug(directory.toString() + " " + name);
274: return readObjectFromBufferedFileObject(file);
275: }
276:
277: /**
278: * Read the contents of the provided file name residing in the provided directory.
279: * Return the contents as an Object.
280: *
281: * @param fileWithPath
282: * @return
283: * @throws IOException
284: * @throws ClassNotFoundException
285: */
286: public static Object readObjectFromFileWithPath(String fileWithPath)
287: throws IOException, ClassNotFoundException {
288: return readObjectFromBufferedFileObject(new File(fileWithPath));
289: }
290:
291: /**
292: * Redirect standard output to the log file.
293: */
294: public static void redirectStandardOutput() {
295: redirectStandardOutput(getLogFileName());
296: }
297:
298: /**
299: * Redirect standard output to the provided File.
300: * @param file
301: */
302: public static void redirectStandardOutput(File file) {
303: try {
304: log.debug("redirectStandardOutput to "
305: + file.getAbsolutePath());
306: PrintStream stdout = new PrintStream(new FileOutputStream(
307: file));
308: System.setOut(stdout);
309: } catch (Exception e) {
310: log.debug("Unable to redirect stdout to "
311: + file.getAbsolutePath());
312: }
313: }
314:
315: /**
316: * Redirect standard output to the provided file name.
317: * @param file
318: */
319: public static void redirectStandardOutput(String fileName) {
320: redirectStandardOutput(new File(fileName));
321: }
322:
323: /**
324: * Return the contents of the provided file as a String.
325: * @param file
326: * @return
327: */
328: public static String stringFromFile(File file) {
329: return contentsOfFile(file);
330: }
331:
332: /**
333: * Return the contents of the provided file name as a String.
334: * @param file
335: * @return
336: */
337: public static String stringFromFile(String fileName) {
338: return contentsOfFile(new File(fileName));
339: }
340:
341: /**
342: * Convert the provided String into the provided File.
343: * @param string
344: * @param file
345: */
346: public static void stringToFile(String string, File file) {
347:
348: try {
349: PrintWriter out = new PrintWriter(new FileWriter(file));
350: out.print(string);
351: out.close();
352: } catch (FileNotFoundException fnfe) {
353: String msg = "File not found exception: " + file;
354: } catch (IOException ioe) {
355: String msg = "IO Exception writing object output stream to file: "
356: + file;
357: }
358: }
359:
360: /**
361: * Convert the provided String into a File of the provided file name.
362: * @param string
363: * @param file
364: */
365: public static void stringToFile(String string, String fileString) {
366:
367: stringToFile(string, new File(fileString));
368: }
369:
370: /**
371: * Convert the provided String into the provided FileOutputStream.
372: * @param string
373: * @param fos
374: * @throws IOException
375: */
376: public static void stringToFileOutputStream(String string,
377: FileOutputStream fos) throws IOException {
378: log.debug("");
379: fos.write(string.getBytes());
380: }
381:
382: /**
383: * Write the provided object to a file of the provided directory and file name.
384: * @param object
385: * @param directory
386: * @param name
387: * @throws IOException
388: */
389: public static void writeObjectToFile(Object object, File directory,
390: String name) throws IOException {
391: ObjectOutputStream oos;
392: File file;
393:
394: log.debug("creating file " + name + " in "
395: + directory.toString());
396: file = new File(directory, name);
397: writeObjectToFileObject(object, file);
398: }
399:
400: /**
401: * Write the provided object to the provided File.
402: * @param object
403: * @param file
404: * @throws IOException
405: */
406: public static void writeObjectToFileObject(Object object, File file)
407: throws IOException {
408: ObjectOutputStream oos = null;
409: log.debug("creating output stream on file...");
410: oos = new ObjectOutputStream(new FileOutputStream(file));
411: log.debug("writing object to stream...");
412: oos.writeObject(object);
413: log.debug("closing stream...");
414: oos.close();
415: }
416:
417: /**
418: * Write the provided object to the provided file name.
419: * @param object
420: * @param fileAndPath
421: * @throws IOException
422: */
423: public static void writeObjectToFileWithPath(Object object,
424: String fileAndPath) throws IOException {
425: writeObjectToFileObject(object, new File(fileAndPath));
426: }
427:
428: /**
429: * Write the provided iterator to a file of the provided file name.
430: * @param it
431: * @param fileName
432: * @throws IOException
433: */
434: public static void iteratorToFile(Iterator it, String fileName)
435: throws IOException {
436: log.debug("");
437: FileOutputStream stream = new FileOutputStream(fileName);
438: while (it.hasNext()) {
439: stringToFileOutputStream(it.next() + "\n", stream);
440: }
441:
442: }
443:
444: /**
445: * Return the provided File as a BufferedReader
446: * @param file
447: * @return
448: * @throws FileNotFoundException
449: */
450: public static java.io.BufferedReader getBufferedReaderFromFile(
451: File file) throws FileNotFoundException {
452: BufferedReader bufferedReader = null;
453: FileReader frdr = new FileReader(file);
454: bufferedReader = new BufferedReader(frdr);
455: return bufferedReader;
456: }
457:
458: /**
459: * Return the provided file name as a BufferedReader
460: * @param fileString
461: * @return
462: * @throws FileNotFoundException
463: */
464: public static java.io.BufferedReader getBufferedReaderFromFile(
465: String fileString) throws FileNotFoundException {
466: return getBufferedReaderFromFile(new File(fileString));
467: }
468:
469: public static String getExceptionMessage(Exception e, File file) {
470: return file.toString() + ": " + e.toString() + " Msg: "
471: + e.getMessage();
472: }
473:
474: /**
475: * Return the name of the log file.
476: * @return
477: */
478: public static String getLogFileName() {
479:
480: // Create a new output stream for the standard output.
481: java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(
482: "MMddyy.HHmmssSSS");
483: String fileName = null;//PropertyUtility.getBaseDirectory() + "/logs/." + formatter.format(new java.util.Date()) + ".log";
484:
485: return fileName;
486: }
487:
488: /**
489: * Return a File for an existing file. If we can't find it by the fileName,
490: * find it in the classpath. If that fails, return null.
491: * @param fileName
492: * @return
493: */
494: public static File findExistingFile(String fileName) {
495: File file = null;
496: file = new File(fileName);
497: if (!file.exists()) {
498: file = null;
499: log.debug("find as resource");
500: URL url = FileUtility.class.getResource("/" + fileName);
501: if (url != null) {
502: String urlFileName = url.getFile();
503: file = new File(urlFileName);
504: }
505: }
506:
507: if (file != null) {
508: log.debug("file " + file.getAbsolutePath() + " "
509: + file.exists());
510: } else {
511: log.debug("file null");
512: }
513: return file;
514: }
515:
516: /**
517: * Return the provided InputStream as a String
518: * @param inputStream
519: * @return
520: */
521: public static String streamToString(InputStream inputStream) {
522: String s = new String();
523: char[] buff = new char[50000];
524: try {
525: InputStreamReader reader = new InputStreamReader(
526: inputStream);
527: int nch;
528: while ((nch = reader.read(buff, 0, buff.length)) != -1) {
529: s = s + new String(buff, 0, nch);
530: }
531: } catch (java.io.IOException ex) {
532: s = null;
533: }
534: return s;
535: }
536:
537: }
|