使用IO流实现文件复制

使用IO流实现文件复制

在学习了一些文件相关知识和io流的一些知识以后,写了个小测试类来实现文件和文件夹的创建和文件复制。

public class Copy {
    public static void main(String[] args) {
        try {
            //创建文件并输入内容
            File file = new File("D:\\temp\\temp.txt");
            boolean newFile = file.createNewFile();
            FileOutputStream outputStream = new FileOutputStream("D:\\temp\\temp.txt");
            outputStream.write("hello world".getBytes());
            //创建文件夹并在文件夹中创建文件
            File file1 = new File("D:\\temp\\temp");
            if (!file1.exists()){
                file1.mkdir();
            }
            File file2 = new File("D:\\temp\\temp\\temp.txt");
            if (!file1.exists()){
                file1.createNewFile();
            }
            //读出旧文件内容,写进新文件中
            FileOutputStream outputStream1 = new FileOutputStream("D:\\temp\\temp\\temp.txt");
            FileInputStream fileInputStream = new FileInputStream("D:\\temp\\temp.txt");
            int ch;
            while((ch=fileInputStream.read()) != -1){
                System.out.println((char)ch);
                outputStream1.write(ch);
            }
            fileInputStream.close();
            outputStream1.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在这个过程中也遇到了一些问题,因此记录下来,以供以后避坑。
首先,一开始,我在复制文件这一块是这么写的:

while((fileInputStream.read()) != -1){
System.out.println((char)fileInputStream.read());
outputStream1.write(fileInputStream.read());
}

这样就导致读出来的文件内容只有一半,写入的和读出的还不一样。
经过一番尝试改成了这样,问题得到了解决。

int ch;
while((ch=fileInputStream.read()) != -1){
System.out.println((char)ch);
outputStream1.write(ch);
}

原因在于fileInputStream.read()方法读取数据时,会使缓冲区数据减少一位,并返回一个经过编码的int型数字,由于while里面调用了一次方法,write里又调用了一次方法,所以导致打印出来的字符串和写入新文件的字符串都只有一半。问题得到解决。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值