Engineering Full Stack Apps with Java and JavaScript
Need to copy a file using BufferedInputStream and BufferedOutputStream.
BufferedInputStream adds the ability to buffer the input and to support the mark and reset methods, using a FileInputStream. Similarly a BufferedOutputStream writes to the file using FileOutputStream only when the buffer is full, not for every byte, and this reduces the actual file writes and hence improve efficiency.
import java.io.*;
public class FileCopierBuffered {
public static void main(String[] args) throws IOException {
FileInputStream fin = new FileInputStream("myFile.txt");
BufferedInputStream bin = new BufferedInputStream(fin);
System.out.println("Is markable? " + bin.markSupported());
FileOutputStream fout = new FileOutputStream("myFileOut.txt", true);
BufferedOutputStream bout = new BufferedOutputStream(fout);
int b = bin.read();
boolean markDone = false;
boolean resetDone = false;
while (b != -1) {
char ch = (char) b;
System.out.println(ch);
if ((ch == 'c') && !markDone) {
bin.mark(512);
markDone = true;
}
if ((ch == 'd') && !resetDone) {
bin.reset();
resetDone = true;
}
bout.write(ch);
b = bin.read();
}
bout.close();
bin.close();
}
}
If input file contains:
aaaa
bbbb
cccc
dddd
Output file will contain:
aaaa
bbbb
cccc
dccc
dddd
We marked after the first c and then reset after the first d.
To avoid marking and resetting again and again we have used two Boolean variables markDone and resetDone and will set them on first marking and first resetting respectively.