当前位置: 代码迷 >> J2SE >> 一个IO的小疑点 各位大神
  详细解决方案

一个IO的小疑点 各位大神

热度:15   发布时间:2016-04-23 20:37:45.0
一个IO的小问题 求助各位大神
自己动手写了BufferedInputStream类中的read方法   
写完之后小小的测试了一下
复制文本文档没啥问题,也不少字节



但是复制图片怎么就少字节了。。。。



/*
自定义一个字节缓冲区类,写一个和BufferedInputStream一样的read()方法
为了代码简洁,没有处理异常
*/
import java.io.*;
public class MyBufferedInputStreamDemo{
public static void main(String[] args)throws IOException{
FileInputStream fis=new FileInputStream("1.jpg");
FileOutputStream fos=new FileOutputStream("CopyPic_1.jpg");

        MyBufferedInputStream mis=new MyBufferedInputStream(fis);

int by;
while((by=mis.MyRead())!=-1){
fos.write(by);
}
mis.MyClose();
fos.close();
}
}
class MyBufferedInputStream{
private InputStream in;
private byte[] buf=new byte[1024];//缓冲容器
private int i;//数组有效元素个数
private int len=0;//判断指针
MyBufferedInputStream(InputStream in){
this.in=in;
}
public int MyRead()throws IOException{

//数组为空或者已取完,进行存储
int by=0;
if(len==0){
while(true){
by=in.read();
if(len<1024&&by!=-1){
buf[len]=(byte)by;
len++;
i=len;
}else{
break;
}
}
}

//取元素
if(len>0){
int x=i-len;
            //System.out.println("x="+x);
len--;
return buf[x]&255;
}else{
return -1;
}
}
public void MyClose()throws IOException{
in.close();
}
}


各种无脑测试之后发现了一点。。。。这个图片是21827字节
一共要存储22次,前21次数组存满,最后一次存21827-1024*21=323个字节
但是我在最后打印x时,只有301个字节

一共少了22个字节
而且两张图片的的字节数也差这么多...
而且也刚好是操作数组的次数。。。。。说明数组中要么一个没存进去,要么没取出来,但是代码我实在不知道哪出问题了
搞了半天啊  不知道这22个字节跑哪去了。。。求各位大神指教
对了,Copy的图片能打开,但是后半截很模糊,和毁掉了的照片一样;
------解决方案--------------------


/*
 自定义一个字节缓冲区类,写一个和BufferedInputStream一样的read()方法
 为了代码简洁,没有处理异常
 */
import java.io.*;

public class MyBufferedInputStreamDemo {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("d:\\zp.jpg");
FileOutputStream fos = new FileOutputStream("d:\\zp1.jpg");

MyBufferedInputStream mis = new MyBufferedInputStream(fis);

int by;
while ((by = mis.MyRead()) != -1) {
fos.write(by);
}
mis.MyClose();
fos.close();
}
}

class MyBufferedInputStream {
private InputStream in;
private byte[] buf = new byte[1024];// 缓冲容器
private int i;// 数组有效元素个数
private int len = 0;// 判断指针

private boolean finished;

MyBufferedInputStream(InputStream in) {
this.in = in;
finished = false;
}

public int MyRead() throws IOException {

// 数组为空或者已取完,进行存储
int by = 0;
if (len == 0 && !finished) {
while (true) {
by = in.read();
if (by == -1) {
this.finished = true;
break;
}
buf[len] = (byte) by;
len++;
if (len == 1024) {
i = len;
break;
}
}
}

// 取元素
if (len > 0) {
int x = i - len;
// System.out.println("x="+x);
len--;
return buf[x] & 255;
} else {
return -1;
}
}

public void MyClose() throws IOException {
in.close();
}
}




你的程序逻辑就有问题,我给你 改了一下,测试可行。
  相关解决方案