import java.util.zip.ZipOutputStream;
/**
- * This class offer some utilities based around Streams.
+ * This class offer some utilities based around Streams and Files.
*
* @author niki
*/
*/
public static void write(InputStream in, OutputStream out)
throws IOException {
- byte buffer[] = new byte[4069];
+ byte buffer[] = new byte[4096];
for (int len = 0; (len = in.read(buffer)) > 0;) {
out.write(buffer, 0, len);
}
dir.mkdirs();
}
- FileWriter writerVersion = new FileWriter(new File(dir, filename));
+ writeSmallFile(new File(dir, filename), content);
+ }
+
+ /**
+ * Write the {@link String} content to {@link File}.
+ *
+ * @param file
+ * the {@link File} to write
+ * @param content
+ * the content
+ *
+ * @throws IOException
+ * in case of I/O error
+ */
+ public static void writeSmallFile(File file, String content)
+ throws IOException {
+ FileWriter writerVersion = new FileWriter(file);
try {
writerVersion.write(content);
} finally {
*/
public static InputStream forceResetableStream(InputStream in)
throws IOException {
- MarkableFileInputStream tmpIn = null;
- File tmp = null;
-
boolean resetable = in.markSupported();
if (resetable) {
try {
return in;
}
- tmp = File.createTempFile(".tmp-stream", ".tmp");
+ final File tmp = File.createTempFile(".tmp-stream.", ".tmp");
try {
write(in, tmp);
- tmpIn = new MarkableFileInputStream(new FileInputStream(tmp));
- return tmpIn;
- } finally {
- try {
- if (tmpIn != null) {
- tmpIn.close();
+ in.close();
+
+ final FileInputStream fis = new FileInputStream(tmp);
+ return new MarkableFileInputStream(fis) {
+ @Override
+ public void close() throws IOException {
+ try {
+ try {
+ super.close();
+ } finally {
+ try {
+ fis.close();
+ } catch (IOException e) {
+ }
+ }
+ } finally {
+ tmp.delete();
+ }
}
- } finally {
- tmp.delete();
- }
+ };
+ } catch (IOException e) {
+ tmp.delete();
+ throw e;
}
}
return array;
}
+
+ /**
+ * Convert the {@link File} into a byte array.
+ *
+ * @param file
+ * the input {@link File}
+ *
+ * @return the array
+ *
+ * @throws IOException
+ * in case of I/O error
+ */
+ public static byte[] toByteArray(File file) throws IOException {
+ FileInputStream fis = new FileInputStream(file);
+ try {
+ return toByteArray(fis);
+ } finally {
+ fis.close();
+ }
+ }
}