public class ByteStreamDemo {
public static void main(String args) throws IOException{
FileInputStream fip = new FileInputStream("f:\\123.mp3");
FileOutputStream fop = new FileOutputStream("f:\\WRITER\\123.mp3");

byte[] buf = new byte[1024];
int i = 0;
while((i=fip.read(buf))!=-1){
fop.write(buf,0,i);

}


fip.close();
fop.close();
}
}
我用这段代码复制txt文件没问题,但换成mp3或者jpg文件就不行了,运行后没有报错,但是去f:\WRITER目录查看时却没有文件,这是为什么?都没报错,将代码原封不动,只是将文件换成txt就没问题,mp3和jpg文件也是存在的,真是疑惑。
自学中没地请教,希望各位大神不吝赐教,谢谢!

解决方案 »

  1.   

    用DataInputStream和FileInputStream可以操作二进制文件,图片音频文件都行
      

  2.   

    我试了一下,没有啥问题,代码如下:public class TestCopyJpg { public static void main(String[] args) throws IOException{
            FileInputStream fip = new FileInputStream("c:\\a.JPG");
            FileOutputStream fop = new FileOutputStream("d:\\a.JPG");
             
            byte[] buf = new byte[1024];
            int i = 0;
            while((i=fip.read(buf))!=-1){
                fop.write(buf,0,i);
                 
            }
            fip.close();
            fop.close();
        }

    }
      

  3.   


    你这程序是可以使用的,我试了图片和音乐。但是不同的电脑系统对分隔符路径识别而不一样,建议规范化。还有你试试flush一下,也可能你的电脑阻塞。File file=new File("C:"+File.separator+"1.jpg");
    FileInputStream in=null;
    FileOutputStream out=null;
    try {
    in=new FileInputStream(file);
    out=new FileOutputStream(new File("C:"+File.separator+"2.jpg"));
    byte [] b=new byte[1024];
    int len=0;
    while ((len=in.read(b))!=-1) {
    out.write(b, 0, len);
    out.flush();
    }
    System.out.println("文件复制成功");
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    try {
    in.close();
    out.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
      

  4.   

    测试过了,代码没有问题 。 你注意一下你的MP3和jpg原文件有没有格式后缀, 你再在while循环外面输出一句话,看看程序有没有走到这一步