我记得有段时间学clojure的IO操作的时候,他没有暴露出操作细节,比如
char [] buffer = new char[1024];
int length = in.read(buffer,0,1024);
while(length != -1) {
out.write(buffer,0,1024);
lenght = in.read(buffer,0,1024);
}
out.flush();
而是直接
(require '[clojure.java.io :as io])
(io/copy in out)
这里in: input-stream,reader,(也可以是File)
这里out: output-stream,writer,(也可以是File)
总的来说,这是一个读取数据,再写入数据的过程,他可以概括一部分IO操作,包括网络通信
于是我有了在Java中实现这个io/copy
的想法
import java.io.*;
import static java.lang.System.out;
class FileProxy {
// Copy(in,out)
// Copy(in,out,buffer-size)
static int buffer_size=1024;
static void Copy(InputStream in,OutputStream out) throws IOException {
byte [] buffer = new byte[buffer_size];
int length = in.read(buffer,0,buffer_size);
while(length != -1) {
out.write(buffer,0,length);
length = in.read(buffer,0,buffer_size);
}
out.flush();
}
static void Copy(InputStream in,OutputStream out,int __buffer_size) throws IOException {
byte [] buffer = new byte[__buffer_size];
int length = in.read(buffer,0,buffer_size);
while(length != -1) {
out.write(buffer,0,length);
length = in.read(buffer,0,length);
}
out.flush();
}
static void Copy(Reader in,Writer out) throws IOException {
char [] buffer = new char[buffer_size];
int length = in.read(buffer,0,buffer_size);
while(length != -1) {
out.write(buffer,0,length);
length = in.read(buffer,0,buffer_size);
}
out.flush();
}
static void Copy(Reader in,Writer out,int __buffer_size) throws IOException {
char [] buffer = new char[__buffer_size];
int length = in.read(buffer,0,buffer_size);
while(length != -1) {
out.write(buffer,0,length);
length = in.read(buffer,0,buffer_size);
}
out.flush();
}
}