private static final int buff = 1024;

public static void main(String []args) throws Exception{

FileInputStream fis = new FileInputStream("f:\\test.mp3");
FileOutputStream fos = new FileOutputStream("f:\\copyOftest.mp3");

byte [] bytes = new byte[buff];

while(fis.read(bytes)!= -1){
fos.write(bytes);
}
fis.close();
fos.close();
}
就这段代码,当我们往文件写字节数组时,应该是将整个数组内容全部写出去,前面几次没问题,但是当文件大小不是1024的整数倍时,那也会把后面的写进去啊,但是程序运行并没有问题,请各位帮忙解释一下,谢谢

解决方案 »

  1.   

    需要判断下文件大小
    读出源文件大小除以1024 得到商和余数
    循环读取、写入的时候循环商次
    最后读写一次,buff大小设定为余数大小
      

  2.   

    把byte [] bytes = new byte[buff];while(fis.read(bytes)!= -1){
    fos.write(bytes);
    }
    改为  
    byte [] bytes = new byte[buff];
    int len = 0;
    while((len=fis.read(bytes))!= -1){
         fos.write(new String(bytes,0,len));
      

  3.   

    byte [] bytes = new byte[ fis.available()];
      

  4.   

    屌了...这样写会对吗...MP3文件,你用string往里面写???
    fos.write(buf,0,len);
      

  5.   


            static void t7(){
    int readLen = 0;
    InputStream in = null;
    OutputStream out = null;
    byte[] buff = new byte[512];

    try{
    //in = ...;
    //out = ...;


    while(-1 != (readLen=in.read(buff))){
    out.write(buff, 0, readLen);
    }
    }catch(Exception ex){
    ex.printStackTrace();
    }
    }
      

  6.   

    out.flush();
    默认是1024个字节,如果你不够的话他是不会主动去flush的,如果碰巧不能整除,那么你会发现最后面少了些数据。
    不信你可以弄个txt文件试试。
      

  7.   

    或许mp3最后丢失了几个字节,楼主看不到区别。
    建议用txt文本试试。