001: /*
002: * (C) Copyright 2001 Nabh Information Systems, Inc.
003: *
004: * All copyright notices regarding Nabh's products MUST remain
005: * intact in the scripts and in the outputted HTML.
006: * This program is free software; you can redistribute it and/or
007: * modify it under the terms of the GNU Lesser General Public License
008: * as published by the Free Software Foundation; either version 2.1
009: * of the License, or (at your option) any later version.
010: *
011: * This program is distributed in the hope that it will be useful,
012: * but WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
014: * GNU Lesser General Public License for more details.
015: *
016: * You should have received a copy of the GNU Lesser General Public License
017: * along with this program; if not, write to the Free Software
018: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
019: *
020: */
021:
022: package com.nabhinc.util;
023:
024: import java.io.*;
025:
026: import java.net.MalformedURLException;
027: import java.net.URL;
028:
029: import java.util.Enumeration;
030: import java.util.Properties;
031:
032: /**
033: * Provides utility methods for reading / writing from files / URLs
034: *
035: * @author Padmanabh Dabke
036: * (c) 2001 Nabh Information Systems, Inc. All Rights Reserved.
037: */
038: public class IOUtil {
039:
040: /**
041: * Reads a Java object from the byte array.
042: * @param ser Byte array holding serialized object
043: * @return Deserialized Java object
044: * @exception java.io.IOException Thrown in deserializing the object
045: * @exception ClassNotFoundException A class referenced by
046: * the deserialized object is not found
047: * @exception java.rmi.RemoteException
048: */
049: public static Serializable deserializeObject(byte[] ser)
050: throws java.io.IOException, ClassNotFoundException,
051: java.rmi.RemoteException {
052: if (ser == null)
053: return null;
054: ObjectInputStream ois = new ObjectInputStream(
055: new ByteArrayInputStream(ser));
056: return (Serializable) ois.readObject();
057: }
058:
059: /**
060: * Serializes the given object into a byte array
061: * @param obj
062: * @return Byte array containing serialized object.
063: * @throws IOException
064: */
065: public static byte[] serializeObject(Serializable obj)
066: throws IOException {
067: byte[] result = null;
068: ByteArrayOutputStream bytes = new ByteArrayOutputStream();
069: ObjectOutputStream out = new ObjectOutputStream(bytes);
070: out.writeObject(obj);
071: out.flush();
072: result = bytes.toByteArray();
073: out.close();
074: return result;
075: }
076:
077: /**
078: * Creates a Base 64 encoded string representation of a serialized object
079: * @param obj Object to be serialized
080: * @return String representing the serialized object.
081: * @throws IOException
082: */
083: public static String stringifyObject(Serializable obj)
084: throws IOException {
085: byte[] result = serializeObject(obj);
086: return Base64.encode(result);
087: }
088:
089: /**
090: * Deserializes an object from a string. The string is assumed to be Base64
091: * encoding of the byte array containing the serialized object
092: * @param str Base64 encoded string of serilized object bytes
093: * @return Original object
094: * @throws IOException
095: * @throws ClassNotFoundException
096: */
097: public static Serializable destringifyObject(String str)
098: throws IOException, ClassNotFoundException {
099: byte[] ser = Base64.decode(str);
100: return deserializeObject(ser);
101: }
102:
103: /**
104: * Reads contents of a file as a string and encodes based on character encoding
105: * specified. Default character encoding is UTF-8.
106: * @return String holding the file contents
107: * @param file File to be read
108: * @param charset Characters encoding. The charset's name must be one of name
109: * supported {@link java.nio.charset.Charset charset}
110: * @exception java.io.IOException
111: */
112: public static String getFileContentAsString(File file,
113: String charset) throws java.io.IOException {
114: if (charset == null)
115: charset = "UTF-8";
116:
117: FileInputStream fis = new FileInputStream(file);
118: InputStreamReader fi = new InputStreamReader(fis, charset);
119: // FileReader fi = new FileReader(file);
120: char[] buf = new char[100];
121: StringWriter w = new StringWriter();
122: int bytes = fi.read(buf);
123: while (bytes != -1) {
124: w.write(buf, 0, bytes);
125: bytes = fi.read(buf);
126: }
127: fi.close();
128: w.close();
129: fis.close();
130: return w.toString();
131:
132: }
133:
134: /**
135: * Reads contents of a file as a UTF-8 encoded string.
136: * @param file File to be read
137: * @return Contents of the file with UTF-8 encoded.
138: * @throws java.io.IOException
139: */
140: public static String getFileContentAsString(File file)
141: throws java.io.IOException {
142: return IOUtil.getFileContentAsString(file, "UTF-8");
143:
144: }
145:
146: public static String getInputStreamContentAsString(InputStream is,
147: String charset) throws java.io.IOException {
148: if (charset == null)
149: charset = "UTF-8";
150:
151: InputStreamReader fi = new InputStreamReader(is, charset);
152: // FileReader fi = new FileReader(file);
153: char[] buf = new char[100];
154: StringWriter w = new StringWriter();
155: int bytes = fi.read(buf);
156: while (bytes != -1) {
157: w.write(buf, 0, bytes);
158: bytes = fi.read(buf);
159: }
160: fi.close();
161: w.close();
162: return w.toString();
163:
164: }
165:
166: public static byte[] getFileContentAsBytes(File file)
167: throws java.io.IOException {
168: FileInputStream fi = null;
169: try {
170: byte[] buf = new byte[1000];
171: fi = new FileInputStream(file);
172: ByteArrayOutputStream bos = new ByteArrayOutputStream();
173: int bytes = fi.read(buf);
174: while (bytes != -1) {
175: bos.write(buf, 0, bytes);
176: bytes = fi.read(buf);
177: }
178: return bos.toByteArray();
179: } finally {
180: if (fi != null)
181: fi.close();
182: }
183:
184: }
185:
186: /**
187: * Reads contents of an input stream as a UTF-8 encoded string.
188: * @param is Input stream to be read
189: * @return Contents of the file with UTF-8 encoded.
190: * @throws java.io.IOException
191: */
192: public static String getInputStreamContentAsString(InputStream is)
193: throws java.io.IOException {
194: return IOUtil.getInputStreamContentAsString(is, "UTF-8");
195:
196: }
197:
198: /**
199: * Create a backup (old content) of a file (with extension .bak) and update the content
200: * of the specified file based on UTF-8 charset encoding.
201: * @param file File which content to be updated.
202: * @param newContent New content
203: * @exception java.io.IOException
204: */
205: public static void saveAndBackupFile(File file, String newContent)
206: throws IOException {
207: saveAndBackupFile(file, newContent, "UTF-8");
208: }
209:
210: /**
211: * Create a backup (old content) of a file (with extension .bak) and update the content
212: * of the specified file. Default character encoding is UTF-8, if charset is not specified.
213: * If the file does not exist, it will attempt to create one.
214: * @param file File which content to be updated.
215: * @param newContent New content
216: * @param charset Characters encoding. The charset's name must be one of name
217: * supported {@link java.nio.charset.Charset charset}
218: * @exception java.io.IOException
219: */
220: public static void saveAndBackupFile(File file, String newContent,
221: String charset) throws IOException {
222: if (file.exists()) {
223: if (!file.canWrite())
224: throw new java.io.IOException(
225: "Unable to modify read only file.");
226:
227: if (charset == null)
228: charset = "UTF-8";
229:
230: String content = getFileContentAsString(file, charset);
231: OutputStreamWriter writer = new OutputStreamWriter(
232: new FileOutputStream(new File(file
233: .getAbsolutePath()
234: + ".bak")), charset);
235: writer.write(content);
236: writer.flush();
237:
238: writer = new OutputStreamWriter(new FileOutputStream(file),
239: charset);
240: writer.write(newContent);
241: writer.flush();
242:
243: writer.close();
244: } else {
245: createFile(file.getAbsolutePath(), newContent, charset);
246: }
247: }
248:
249: /**
250: * Create a new file with content and file path specified. It will attempt to
251: * overwrite the existing one if the file is writeable.
252: * @param filePath The file path
253: * @param newContent The file content
254: * @param charset Characters encoding. The charset's name must be one of name
255: * supported {@link java.nio.charset.Charset charset}
256: * @throws IOException Thrown if the file path is not specified or trying to
257: * overwrite read only file.
258: */
259: public static void createFile(String filePath, String newContent,
260: String charset) throws IOException {
261:
262: if (filePath == null)
263: throw new java.io.IOException("File path is missing.");
264:
265: File file = new File(filePath);
266: if (file.exists() && !file.canWrite())
267: throw new java.io.IOException(
268: "Failed to overwrite existing read only file.");
269:
270: if (charset == null)
271: charset = "UTF-8";
272:
273: OutputStreamWriter writer = new OutputStreamWriter(
274: new FileOutputStream(file), charset);
275: writer.write(newContent);
276: writer.flush();
277:
278: writer.close();
279: }
280:
281: /**
282: * Reads properties from a file and merges them with the System properties.
283: * @param file Property file path.
284: * @exception java.io.IOException The property file could not
285: * be found.
286: */
287: public static void loadSystemPropertiesFromFile(String file)
288: throws java.io.IOException {
289: FileInputStream is = new FileInputStream(file);
290: System.getProperties().load(is);
291: }
292:
293: /**
294: * Reads properties from a URL and merges them with the System properties.
295: * @param file Property file path.
296: * @exception java.io.IOException The property file could not be found.
297: */
298: public static void loadSystemPropertiesFromURL(String urlStr)
299: throws java.io.IOException, MalformedURLException {
300: URL url = new URL(urlStr);
301: InputStream is = url.openStream();
302: System.getProperties().load(is);
303: }
304:
305: /**
306: * Merges given properties with system properties.
307: */
308: public static void mergeWithSystemProperties(
309: java.util.Properties props) {
310: Enumeration list = props.keys();
311: Object key = null;
312: Properties sysprops = System.getProperties();
313:
314: while (list.hasMoreElements()) {
315: key = list.nextElement();
316: sysprops.put(key, props.get(key));
317: }
318: }
319:
320: /**
321: * Reads contents of a URL as a string.
322: * @return String holding the file contents
323: * @param file File to be read
324: * @exception java.io.IOException
325: */
326: public static String getURLContentAsString(String urlStr)
327: throws java.io.IOException {
328: URL url = new URL(urlStr);
329: InputStreamReader fi = new InputStreamReader(url.openStream());
330: char[] buf = new char[100];
331: StringWriter w = new StringWriter();
332: int bytes = fi.read(buf);
333: while (bytes != -1) {
334: w.write(buf, 0, bytes);
335: bytes = fi.read(buf);
336: }
337: fi.close();
338: w.close();
339: return w.toString();
340:
341: }
342:
343: /**
344: * Delete a file.
345: * @param filename File to be deleted.
346: * @throws IOException If the file is not exist, or
347: * a directory, or not able to be deleted.
348: */
349: public static void deleteFile(String filename) throws IOException {
350: File file = new File(filename);
351: if (file.isDirectory()) {
352: throw new IOException("Error: " + filename
353: + " is not a file.");
354: }
355: if (file.exists() == false) {
356: throw new IOException("Error: File is not exist: "
357: + filename);
358: }
359: if (file.delete() == false) {
360: throw new IOException("Error: Cannot delete file: "
361: + filename);
362: }
363: }
364:
365: public static byte[] getBytes(InputStream inputStream)
366: throws IOException {
367: ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
368: 1024);
369: byte[] block = new byte[512];
370: while (true) {
371: int readLength = inputStream.read(block);
372: if (readLength == -1)
373: break;// end of file
374: byteArrayOutputStream.write(block, 0, readLength);
375: }
376: byte[] retValue = byteArrayOutputStream.toByteArray();
377: byteArrayOutputStream.close();
378: return retValue;
379: }
380:
381: /**
382: * Utility method to convert values in specified properties object to UTF-8.
383: * @param props The Properties object which values to be converted.
384: * @param fromCharset Characters encoding. The charset's name must be one of name
385: * supported {@link java.nio.charset.Charset charset}
386: * @throws IOException
387: */
388: public static void convertToUTF(Properties props, String fromCharset)
389: throws IOException {
390: if (fromCharset == null)
391: fromCharset = "ISO-8859-1";
392: for (java.util.Iterator iter = props.entrySet().iterator(); iter
393: .hasNext();) {
394: final java.util.Map.Entry entry = (java.util.Map.Entry) iter
395: .next();
396: final String key = (String) entry.getKey();
397: final String value = (String) entry.getValue();
398:
399: byte[] bytes = value.getBytes(fromCharset);
400:
401: final String convertedValue = new String(bytes, "UTF-8");
402: if (!value.equals(convertedValue))
403: props.put(key, convertedValue);
404: }
405: }
406:
407: public static boolean deleteDirectory(File dir) {
408: File[] members = dir.listFiles();
409: for (int i = 0; i < members.length; i++) {
410: if (members[i].isFile())
411: members[i].delete();
412: else
413: deleteDirectory(members[i]);
414: }
415: return dir.delete();
416: }
417:
418: public static void copyFile(File srcFile, File destFile,
419: boolean overwrite) throws IOException {
420: if (destFile.exists())
421: if (!overwrite || !destFile.canWrite())
422: throw new IOException(
423: "Destination file exists. File cannot be overwritten.");
424: copyFile(srcFile, destFile);
425: }
426:
427: public static void copyFile(File srcFile, File destFile)
428: throws IOException {
429: FileInputStream fis = null;
430: FileOutputStream fos = null;
431:
432: try {
433: fis = new FileInputStream(srcFile);
434: fos = new FileOutputStream(destFile);
435: byte[] buf = new byte[1000];
436: int numBytes = fis.read(buf);
437: while (numBytes != -1) {
438: fos.write(buf, 0, numBytes);
439: numBytes = fis.read(buf);
440: }
441: } finally {
442: if (fis != null)
443: fis.close();
444: if (fos != null)
445: fos.close();
446: }
447: }
448:
449: public static void copyDirectory(File srcDir, File destDir)
450: throws IOException {
451: File[] members = srcDir.listFiles();
452: destDir.mkdir();
453: for (int i = 0; i < members.length; i++) {
454: if (members[i].isFile())
455: copyFile(members[i], new File(destDir, members[i]
456: .getName()), true);
457: else
458: copyDirectory(members[i], new File(destDir, members[i]
459: .getName()));
460: }
461:
462: }
463:
464: public static void saveInputStreamContentToFile(InputStream is,
465: String filePath) throws java.io.IOException {
466:
467: FileOutputStream out = new FileOutputStream(filePath);
468: byte[] buf = new byte[1000];
469: int bytes = is.read(buf);
470: while (bytes != -1) {
471: out.write(buf, 0, bytes);
472: bytes = is.read(buf);
473: }
474: out.close();
475:
476: }
477:
478: }
|