/*
* (C) Copyright 2001 Nabh Information Systems, Inc.
*
* All copyright notices regarding Nabh's products MUST remain
* intact in the scripts and in the outputted HTML.
* This program 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*
*/
package com.nabhinc.util;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
/**
* Provides utility methods for reading / writing from files / URLs
*
* @author Padmanabh Dabke
* (c) 2001 Nabh Information Systems, Inc. All Rights Reserved.
*/
public class IOUtil {
/**
* Reads a Java object from the byte array.
* @param ser Byte array holding serialized object
* @return Deserialized Java object
* @exception java.io.IOException Thrown in deserializing the object
* @exception ClassNotFoundException A class referenced by
* the deserialized object is not found
* @exception java.rmi.RemoteException
*/
public static Serializable deserializeObject(byte[] ser)
throws java.io.IOException, ClassNotFoundException, java.rmi.RemoteException {
if (ser == null)
return null;
ObjectInputStream ois =
new ObjectInputStream(new ByteArrayInputStream(ser));
return (Serializable) ois.readObject();
}
/**
* Serializes the given object into a byte array
* @param obj
* @return Byte array containing serialized object.
* @throws IOException
*/
public static byte[] serializeObject(Serializable obj) throws IOException {
byte[] result = null;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bytes);
out.writeObject(obj);
out.flush();
result = bytes.toByteArray();
out.close();
return result;
}
/**
* Creates a Base 64 encoded string representation of a serialized object
* @param obj Object to be serialized
* @return String representing the serialized object.
* @throws IOException
*/
public static String stringifyObject(Serializable obj) throws IOException {
byte[] result = serializeObject(obj);
return Base64.encode(result);
}
/**
* Deserializes an object from a string. The string is assumed to be Base64
* encoding of the byte array containing the serialized object
* @param str Base64 encoded string of serilized object bytes
* @return Original object
* @throws IOException
* @throws ClassNotFoundException
*/
public static Serializable destringifyObject(String str) throws IOException,
ClassNotFoundException {
byte[] ser = Base64.decode(str);
return deserializeObject(ser);
}
/**
* Reads contents of a file as a string and encodes based on character encoding
* specified. Default character encoding is UTF-8.
* @return String holding the file contents
* @param file File to be read
* @param charset Characters encoding. The charset's name must be one of name
* supported {@link java.nio.charset.Charset charset}
* @exception java.io.IOException
*/
public static String getFileContentAsString(File file, String charset)
throws java.io.IOException {
if (charset == null) charset = "UTF-8";
FileInputStream fis = new FileInputStream(file);
InputStreamReader fi = new InputStreamReader(fis, charset);
// FileReader fi = new FileReader(file);
char[] buf = new char[100];
StringWriter w = new StringWriter();
int bytes = fi.read(buf);
while (bytes != -1) {
w.write(buf, 0, bytes);
bytes = fi.read(buf);
}
fi.close();
w.close();
fis.close();
return w.toString();
}
/**
* Reads contents of a file as a UTF-8 encoded string.
* @param file File to be read
* @return Contents of the file with UTF-8 encoded.
* @throws java.io.IOException
*/
public static String getFileContentAsString(File file)
throws java.io.IOException {
return IOUtil.getFileContentAsString (file, "UTF-8");
}
public static String getInputStreamContentAsString(InputStream is, String charset)
throws java.io.IOException {
if (charset == null) charset = "UTF-8";
InputStreamReader fi = new InputStreamReader(is, charset);
// FileReader fi = new FileReader(file);
char[] buf = new char[100];
StringWriter w = new StringWriter();
int bytes = fi.read(buf);
while (bytes != -1) {
w.write(buf, 0, bytes);
bytes = fi.read(buf);
}
fi.close();
w.close();
return w.toString();
}
public static byte[] getFileContentAsBytes(File file)
throws java.io.IOException {
FileInputStream fi = null;
try {
byte[] buf = new byte[1000];
fi = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int bytes = fi.read(buf);
while (bytes != -1) {
bos.write(buf, 0, bytes);
bytes = fi.read(buf);
}
return bos.toByteArray();
} finally {
if (fi != null) fi.close();
}
}
/**
* Reads contents of an input stream as a UTF-8 encoded string.
* @param is Input stream to be read
* @return Contents of the file with UTF-8 encoded.
* @throws java.io.IOException
*/
public static String getInputStreamContentAsString(InputStream is)
throws java.io.IOException {
return IOUtil.getInputStreamContentAsString (is, "UTF-8");
}
/**
* Create a backup (old content) of a file (with extension .bak) and update the content
* of the specified file based on UTF-8 charset encoding.
* @param file File which content to be updated.
* @param newContent New content
* @exception java.io.IOException
*/
public static void saveAndBackupFile (File file, String newContent)
throws IOException {
saveAndBackupFile(file, newContent, "UTF-8");
}
/**
* Create a backup (old content) of a file (with extension .bak) and update the content
* of the specified file. Default character encoding is UTF-8, if charset is not specified.
* If the file does not exist, it will attempt to create one.
* @param file File which content to be updated.
* @param newContent New content
* @param charset Characters encoding. The charset's name must be one of name
* supported {@link java.nio.charset.Charset charset}
* @exception java.io.IOException
*/
public static void saveAndBackupFile (File file, String newContent, String charset)
throws IOException {
if (file.exists()) {
if (!file.canWrite())
throw new java.io.IOException("Unable to modify read only file.");
if (charset == null) charset = "UTF-8";
String content = getFileContentAsString(file, charset);
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(
new File(file.getAbsolutePath() + ".bak")), charset);
writer.write(content);
writer.flush();
writer = new OutputStreamWriter(new FileOutputStream (file), charset);
writer.write(newContent);
writer.flush();
writer.close();
} else {
createFile (file.getAbsolutePath(), newContent, charset);
}
}
/**
* Create a new file with content and file path specified. It will attempt to
* overwrite the existing one if the file is writeable.
* @param filePath The file path
* @param newContent The file content
* @param charset Characters encoding. The charset's name must be one of name
* supported {@link java.nio.charset.Charset charset}
* @throws IOException Thrown if the file path is not specified or trying to
* overwrite read only file.
*/
public static void createFile (String filePath, String newContent, String charset)
throws IOException {
if (filePath == null)
throw new java.io.IOException("File path is missing.");
File file = new File(filePath);
if (file.exists() && !file.canWrite())
throw new java.io.IOException("Failed to overwrite existing read only file.");
if (charset == null) charset = "UTF-8";
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), charset);
writer.write(newContent);
writer.flush();
writer.close();
}
/**
* Reads properties from a file and merges them with the System properties.
* @param file Property file path.
* @exception java.io.IOException The property file could not
* be found.
*/
public static void loadSystemPropertiesFromFile(String file)
throws java.io.IOException {
FileInputStream is = new FileInputStream(file);
System.getProperties().load(is);
}
/**
* Reads properties from a URL and merges them with the System properties.
* @param file Property file path.
* @exception java.io.IOException The property file could not be found.
*/
public static void loadSystemPropertiesFromURL(String urlStr)
throws java.io.IOException, MalformedURLException {
URL url = new URL(urlStr);
InputStream is = url.openStream();
System.getProperties().load(is);
}
/**
* Merges given properties with system properties.
*/
public static void mergeWithSystemProperties(java.util.Properties props) {
Enumeration list = props.keys();
Object key = null;
Properties sysprops = System.getProperties();
while (list.hasMoreElements()) {
key = list.nextElement();
sysprops.put(key, props.get(key));
}
}
/**
* Reads contents of a URL as a string.
* @return String holding the file contents
* @param file File to be read
* @exception java.io.IOException
*/
public static String getURLContentAsString(String urlStr)
throws java.io.IOException {
URL url = new URL(urlStr);
InputStreamReader fi = new InputStreamReader(url.openStream());
char[] buf = new char[100];
StringWriter w = new StringWriter();
int bytes = fi.read(buf);
while (bytes != -1) {
w.write(buf, 0, bytes);
bytes = fi.read(buf);
}
fi.close();
w.close();
return w.toString();
}
/**
* Delete a file.
* @param filename File to be deleted.
* @throws IOException If the file is not exist, or
* a directory, or not able to be deleted.
*/
public static void deleteFile(String filename) throws IOException {
File file = new File(filename);
if (file.isDirectory()) {
throw new IOException("Error: " + filename + " is not a file.");
}
if (file.exists() == false) {
throw new IOException("Error: File is not exist: " + filename);
}
if (file.delete() == false) {
throw new IOException("Error: Cannot delete file: " + filename);
}
}
public static byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] block = new byte[512];
while (true) {
int readLength = inputStream.read(block);
if (readLength == -1) break;// end of file
byteArrayOutputStream.write(block, 0, readLength);
}
byte[] retValue = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
return retValue;
}
/**
* Utility method to convert values in specified properties object to UTF-8.
* @param props The Properties object which values to be converted.
* @param fromCharset Characters encoding. The charset's name must be one of name
* supported {@link java.nio.charset.Charset charset}
* @throws IOException
*/
public static void convertToUTF (Properties props, String fromCharset)
throws IOException {
if (fromCharset == null) fromCharset = "ISO-8859-1";
for (java.util.Iterator iter = props.entrySet().iterator(); iter.hasNext(); ) {
final java.util.Map.Entry entry = (java.util.Map.Entry) iter.next();
final String key = (String)entry.getKey();
final String value = (String)entry.getValue();
byte[] bytes = value.getBytes(fromCharset);
final String convertedValue = new String(bytes, "UTF-8");
if (!value.equals(convertedValue))
props.put(key, convertedValue);
}
}
public static boolean deleteDirectory(File dir) {
File[] members = dir.listFiles();
for (int i = 0; i < members.length; i++) {
if (members[i].isFile()) members[i].delete();
else deleteDirectory(members[i]);
}
return dir.delete();
}
public static void copyFile(File srcFile, File destFile, boolean overwrite) throws IOException {
if (destFile.exists())
if (!overwrite || !destFile.canWrite())
throw new IOException ("Destination file exists. File cannot be overwritten.");
copyFile (srcFile, destFile);
}
public static void copyFile(File srcFile, File destFile) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
byte[] buf = new byte[1000];
int numBytes = fis.read(buf);
while (numBytes != -1) {
fos.write(buf, 0, numBytes);
numBytes = fis.read(buf);
}
} finally {
if (fis != null) fis.close();
if (fos != null) fos.close();
}
}
public static void copyDirectory(File srcDir, File destDir) throws IOException {
File[] members = srcDir.listFiles();
destDir.mkdir();
for (int i = 0; i < members.length; i++) {
if (members[i].isFile()) copyFile(members[i], new File(destDir, members[i].getName()), true);
else copyDirectory(members[i], new File(destDir, members[i].getName()));
}
}
public static void saveInputStreamContentToFile(InputStream is, String filePath)
throws java.io.IOException {
FileOutputStream out = new FileOutputStream(filePath);
byte[] buf = new byte[1000];
int bytes = is.read(buf);
while (bytes != -1) {
out.write(buf, 0, bytes);
bytes = is.read(buf);
}
out.close();
}
}
|