java读写文件

//向指定文件中写入数据
    public static void writeDataToFile(String content, String filePath) {
        try {
            //创建一个文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            //获取文件输入流的通道
            FileChannel channel = fileOutputStream.getChannel();
            //创建一个字节缓冲区,并制定长度
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            //将要写入到文件中的内容放入缓冲区
            byteBuffer.put(content.getBytes());
            //将byteBuffer进行读写反转
            byteBuffer.flip();
            //将byteBuffer的内容写入通道
            channel.write(byteBuffer);
            //资源关闭
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //从指定文件中读取数据
    public static String readDataFromFile(String filePath) {
        String result = "";
        try {
            //获取文件输入流
            File file = new File(filePath);
            FileInputStream fileInputStream = new FileInputStream(file);
            //获取文件输入流的通道
            FileChannel fileChannel = fileInputStream.getChannel();
            //创建字节缓冲区对象,用于接收通道中的数据
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
            //将通道中的数据写入缓冲区
            fileChannel.read(byteBuffer);
            //将缓冲区的数据返回
            result = new String(byteBuffer.array());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值