我用BufferedReader来进行复制文件,对txt文件拷贝没有问题,但是拷贝其他的文件如pdf,rar等格式的文件就会出现问题,拷贝后的文件大小跟原来的不一样,而且也打不开 文件被破坏了 难道Reader不能复制出文本格式外的文件吗?还有 我用FileChannel也出现同样情况 不知道怎么回事

解决方案 »

  1.   

    BufferedReader是用来操作文本文件的,也就是字符流,无法用来操作像PDF RAR这样的二进制文件,如果你要复制这些文件,可以考虑用FileInputStream FileOutpuStream 然后用相应的Buffer缓冲至于用FileChannel是可以实现复制任何类型的文件,你之所以出问题 肯定是程序的问题,FileChannel是NIO的内容估计你对NIO的几个API操作调用有问题,可以贴程序看看
      

  2.   


    谢谢你的回复 非常抱歉没能及时答复你能给个FileChannel复制大文件的例子吗?
      

  3.   

        // Create channel on the source
        FileChannel srcChannel = new FileInputStream("srcFilename").getChannel();    // Create channel on the destination
        FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel();    // Copy file contents from source to destination
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());    // Close the channels
        srcChannel.close();
        dstChannel.close();
      

  4.   


    如果文件比较大呢?比如说有10G ?这样会OutOfMemory
      

  5.   

    我也写过一些,写了一个关于使用FileInputStream ;FileOutputStream来复制一个文件,
    写的不怎么地, 希望多少有点帮助;
    public class CopyFile {
       public static void main(String[] args) throws IOException {
    int i;
    FileInputStream fin;
    FileOutputStream fou; try {
    fin = new FileInputStream("d:/data/Hi.java");
    } catch (FileNotFoundException e) {
    System.out.println("Input File Not Found");
    return;
    } try {
    fou = new FileOutputStream("d:/data/Array.java");
    } catch (FileNotFoundException e) {
    System.out.println("Error Opening Output File");
    return;
    } try {
    do {
    i = fin.read();
    if (i != -1)
    fou.write(i);
    } while (i != -1);
    } catch (IOException e) {
    System.out.println("File Error");
    }
    fin.close();
    fou.close(); }}
      

  6.   


    谢谢 但是我需要的是FileChannel的例子
      

  7.   


    在此多问一句:*Reader不适合复制文件(如果不知道是何种文件的情况下)?哪些文件时文本文件,哪些是二进制文件?
      

  8.   

    用文本编辑器可以打开直接查看内容的文件一般就是文本文件,二进制文件需要特殊的应用程序才能打开我没有用FileChannel复制过那么大的文件,不清楚复制大文件和一般文件的代码是否一样
      

  9.   


    你的方法适用于复制小一些的文件,为复制很大的文件,修改了你的方法:public static void copy3() throws Exception {
    long start = System.currentTimeMillis();
    System.out.println("start");
    FileChannel channel = new FileInputStream("E:\\test\\JDK6API.chm").getChannel();
    FileChannel channel_out = new FileOutputStream("D:\\JDK6API.chm").getChannel(); long fileSize = channel.size();
    int c = 1024000;
    long end = 0;
    for(long i=0; end<fileSize; i++) {
    System.out.println(i);
    if((i+1)*c >= fileSize) {
    end = fileSize;
    } else {
    end =(i+1)*c; 
    }
    channel_out.transferFrom(channel, i*c, end);
    }

    channel.close();
    channel_out.close();
    long endTime = System.currentTimeMillis();
    System.out.println(endTime -start);
    }
    但是用这个方法复制出错,不管大文件还是小文件,复制后都出问题不知哪里写的不对?