IO 操作文件的代码

该博客展示了如何使用Java的FileInputStream和FileOutputStream类,通过字节流的方式读取一个文件的内容并写入到另一个文件中,实现文件的复制功能。在操作完成后,还强调了必须关闭文件流以防止资源泄露。
摘要由CSDN通过智能技术生成

使用字节流,实现把一个文件里的内容读取出来,写入到另一个文件。

  FileInputStream   读文件
  FileOutputStream  写文件
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestFile {
    public static void main(String[] args) throws IOException {
        //通过简单的程序,把一个文件的内容读取出来,写到另一个文件里(相当于文件拷贝功能)
        String srcPath = "/Users/test1.txt";
        String destPath = "/Users/test2.txt";
        //通过代码实现读取文件
        FileInputStream fileInputStream = new FileInputStream(srcPath);
        //通过代码实现写文件
        FileOutputStream fileOutputStream = new FileOutputStream(destPath);
        //读取并写入
        while (true){
            int ch = fileInputStream.read();

            if (ch == -1){
                break;
            }
            fileOutputStream.write(ch);
        }

        //进行完成记得关闭文件,防止文件资源泄露
        fileOutputStream.close();
        fileInputStream.close();

    }
}

写完文件后一定要记得关闭文件(避免文件泄漏)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值