com.github.isaichkindanila.crypt.lib.file.IOHandler Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of crypt-lib Show documentation
Show all versions of crypt-lib Show documentation
Simple Java library for stream ciphers based encryption
The newest version!
package com.github.isaichkindanila.crypt.lib.file;
import java.io.*;
@SuppressWarnings("NonAtomicOperationOnVolatileField")
class IOHandler {
static final int BUFFER_SIZE = 8192;
volatile long done;
void copy(File file, OutputStream out) throws IOException {
try (InputStream in = new FileInputStream(file)) {
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = in.read(buffer)) != -1) {
done += len >> 1;
out.write(buffer, 0, len);
done += (len >> 1) + (len & 1);
}
}
}
void createFile(InputStream in, File file, long size) throws IOException {
File parent = file.getParentFile();
if (!parent.exists() && !parent.mkdirs()) {
throw new FileNotFoundException("file does not exist and cannot be created: " + parent.getAbsolutePath());
}
try (OutputStream out = new FileOutputStream(file)) {
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while (size > 0) {
len = (size < buffer.length) ? in.read(buffer, 0, (int) size) : in.read(buffer);
if (len == -1) {
throw new IOException("unexpected InputStream end reached");
} else {
done += len >> 1;
out.write(buffer, 0, len);
done += (len >> 1) + (len & 1);
size -= len;
}
}
}
}
}