使用io和nio进行文件拷贝
1、io
@Test
public void iotest() throws Exception {
InputStream in = new FileInputStream("C:\\shit.txt");
OutputStream out = new FileOutputStream("C:\\shit2.txt");
byte[] bytes = new byte[1024];
int len = 0;
while ((len = in.read(bytes)) > 0) {
out.write(bytes, 0, len);
}
in.close();
out.close();
}
2、nio
@Test
public void nioTest() throws Exception {
FileInputStream in = new FileInputStream("C:\\shit.txt");
FileOutputStream out = new FileOutputStream("C:\\shit3.txt");
FileChannel inChannel = in.getChannel();
FileChannel outChannel = out.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.clear();
inChannel.read(byteBuffer);
byteBuffer.flip();
outChannel.write(byteBuffer);
in.close();
out.close();
}
3、InputStream中的read方法
/**
* @param b 缓冲数组
* @param off 读取位置
* @param len 读取长度
* @return
* @throws IOException
*/
public int read(byte b[], int off, int len) throws IOException {
//缓冲数组为空时,直接抛异常
if (b == null) {
throw new NullPointerException();
}
//读取位置小于0或者
//读取长度小于0或者
//读取长度大于可读取的长度
//都会抛出数组越界
else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
}
//读取长度等于0,返回0
else if (len == 0) {
return 0;
}
//读取8个二进制位,并转换成十进制
int c = read();
//-1代表没有可读取的二进制数
if (c == -1) {
return -1;
}
//把读出来的十进制数c转为byte类型
// 赋值到缓冲数组的起始位置
//这几步是为了保证读取的起始位置有值
b[off] = (byte) c;
//循环读取的长度
int i = 1;
try {
for (; i < len; i++) {
//读取,赋值,重复之前的操作
c = read();
if (c == -1) {
break;
}
b[off + i] = (byte) c;
}
} catch (IOException ee) {
}
//读取完毕,i的值应该等于len
return i;
}