Ranphy_小志 2017-03-20 09:13 采纳率: 0%
浏览 789

请看正文,在file IO学习过程中遇到的问题

请教:在使用字节流复制文件时候,使用read重载方法时,运行的结果却不一样。

 public class FileCopyTest {

    public static void main(String[] args) {
        File file2 = new File("F:\\test\\青春.txt");
        CopyByFileInputStream(file2);

    }
    /**
     * 使用字节流复制文件,创建输入输出流,利用循环进行读写
     * @param file
     */
    public static void CopyByFileInputStream(File file) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(file);
            fos = new FileOutputStream("F:\\test\\1\\青春13.txt");
            int by;
            while((by=fis.read())!=-1){
                fos.write(by);
                System.out.println("复制成功");
            }
            byte[] words = new byte[1024];
            while (fis.read() != -1) {
                fis.read(words);
                fos.write(words, 0, words.length);
                System.out.println("复制成功1!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

第一种,使用 read() 读取时图片说明

第二种,使用read(byte[] b) 读取时图片说明

  • 写回答

1条回答 默认 最新

  • 「已注销」 2017-03-20 09:32
    关注
    while (fis.read() != -1) {
                    fis.read(words);
                    fos.write(words, 0, words.length);
                    System.out.println("复制成功1!");
                } 
    

    循环条件中就读取了一次,然后文件指针后移了一次,读取就不正确了

     while (fis.read(words) != -1) {
                    fos.write(words, 0, words.length);
                    System.out.println("复制成功1!");
                } 
    
    评论

报告相同问题?