/*
* Copyright 2013 Pavel Stastny <pavel.stastny at gmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.aplikator.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Pavel Stastny <pavel.stastny at gmail.com>
*/
public class IOUtils {
public static final Logger LOGGER = Logger.getLogger(IOUtils.class.getName());
public static void tryClose(InputStream is) {
try {
if (is != null) {
is.close();
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
public static void tryClose(OutputStream os) {
try {
if (os != null) {
os.close();
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
public static void copyStreams(InputStream is, OutputStream os) throws IOException {
byte[] buffer = new byte[8192];
int read = -1;
while ((read = is.read(buffer)) > 0) {
os.write(buffer, 0, read);
}
}
public static byte[] readBytes(InputStream is, boolean closeInput) throws IOException {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
copyStreams(is, bos);
return bos.toByteArray();
} finally {
if ((is != null) && closeInput) {
is.close();
}
}
}
public static void saveToFile(byte[] data, File file) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(data);
} finally {
if (fos != null) {
fos.close();
}
}
}
}