Skip to content

Instantly share code, notes, and snippets.

@sazid
Last active July 21, 2021 17:54
Show Gist options
  • Save sazid/b63f751ba5334487642fa3db920bc5b5 to your computer and use it in GitHub Desktop.
Save sazid/b63f751ba5334487642fa3db920bc5b5 to your computer and use it in GitHub Desktop.
Trying out different I/O streams in Java.
import java.io.*;
import static java.lang.System.out;
public class Main {
public static void main(String[] args) {
try (var in = new FileInputStream("hello.txt")) {
var buf = new byte[4];
int n = in.read(buf);
while (n != -1) {
out.write(buf, 0, n);
n = in.read(buf);
}
} catch (IOException e) {
e.printStackTrace();
}
out.println();
final var m = new MyData(new int[]{'a', '1', 'P', 'z', 'S', '2', '9', 'b'});
try (var in = m.toInputStream()) {
var buf = new byte[4];
int n = in.read(buf);
while (n != -1) {
out.write(buf, 0, n);
n = in.read(buf);
}
} catch (IOException e) {
e.printStackTrace();
}
out.println();
try (var ignored = new MyResource()) {
out.println("created resource");
}
try (var fout = new FileOutputStream("abc.txt");
var out = new CustomOutputFilter(fout);
var in = m.toInputStream()) {
var buf = new byte[4];
int n = in.read(buf);
while (n != -1) {
out.write(buf, 0, n);
n = in.read(buf);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class CustomOutputFilter extends FilterOutputStream {
public CustomOutputFilter(OutputStream out) {
super(out);
}
@Override
public void write(int b) throws IOException {
if (b >= '0' && b <= '9') {
super.write(b);
} else {
super.write('_');
}
}
}
class MyData {
int[] data;
public MyData(int[] data) {
this.data = data;
}
public InputStream toInputStream() {
return new MyDataInputStream(this);
}
private static class MyDataInputStream extends InputStream {
MyData myData;
int cur = 0;
public MyDataInputStream(MyData myData) {
this.myData = myData;
}
@Override
public int read() {
if (cur < myData.data.length) {
return myData.data[cur++];
}
return -1;
}
}
}
class MyResource implements Closeable, AutoCloseable {
@Override
public void close() {
out.println("I'm closing!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment