org.rajivprab.cava.FileUtilc Maven / Gradle / Ivy
Show all versions of cava Show documentation
package org.rajivprab.cava;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BoundedInputStream;
import org.rajivprab.cava.exception.IOExceptionc;
import org.rajivprab.cava.exception.CheckedExceptionWrapper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
/**
* Utilities related to Files
*
* Created by rprabhakar on 12/15/15.
*/
public class FileUtilc {
// Throws SizeLimitExceededException as appropriate
// Will close the stream on exit
public static void copyToFile(InputStream stream, File file, long maxSize) {
try (InputStream ignored = stream) {
BoundedInputStream boundedStream = new BoundedInputStream(stream, maxSize);
boundedStream.setPropagateClose(false);
FileUtils.copyToFile(boundedStream, file);
// Following read prevents stream from being used outside of this method, if bytes still exist
Validatec.equals(stream.read(), IOUtils.EOF, SizeLimitExceededException.class,
"Stream exceeded " + maxSize / 1024 + " kB");
} catch (IOException e) {
throw new IOExceptionc(e);
}
}
public static void copyToFile(InputStream stream, File file) {
try {
FileUtils.copyToFile(stream, file);
} catch (IOException e) {
throw new IOExceptionc(e);
}
}
public static String readFileToString(File file) {
try {
return FileUtils.readFileToString(file, IOUtilc.CHARSET_USED);
} catch (IOException e) {
throw new IOExceptionc(e);
}
}
public static String readClasspathFile(String path) {
try {
return IOUtilc.toString(ClassLoader.getSystemResourceAsStream(path));
} catch (NullPointerException e) {
throw new IOExceptionc(new FileNotFoundException("Classpath file does not exist: " + path));
}
}
public static File getClasspathFile(String path) {
try {
return new File(ClassLoader.getSystemResource(path).toURI());
} catch (URISyntaxException e) {
throw new CheckedExceptionWrapper(e);
}
}
public static class SizeLimitExceededException extends RuntimeException {
public SizeLimitExceededException(String message) {
super(message);
}
}
}