java nio读取和写入文件


读取

package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.MessageFormat;

public class TestFileChannel {
    public static void main(String[] args) throws IOException {


        FileInputStream fin = new FileInputStream("D:\\temp\\TestService.cs");

        // 获取通道
        FileChannel fc = fin.getChannel();

        // 创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 读取数据到缓冲区
        fc.read(buffer);

        buffer.flip();

        StringBuffer s=new StringBuffer();
        while (buffer.remaining() > 0) {
            byte b = buffer.get();
            s.append((char)b);
            //System.out.print(((char) b));
        }
        System.out.print(s);

        fin.close();


    }
}
View Code

写入

public class Test {
    public static void main(String[] args) throws IOException  {
        File file = new File("data.txt");
        FileOutputStream outputStream = new FileOutputStream(file);
        FileChannel channel = outputStream.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        String string = "java nio";
        buffer.put(string.getBytes());
        buffer.flip();     //此处必须要调用buffer的flip方法
        channel.write(buffer);
        channel.close();
        outputStream.close();
    }  
}
View Code

优质内容筛选与推荐>>
1、ElasticSearch 5学习(5)——第一个例子(很实用)
2、我开发的宣传软件,劲撑广州恒大冲击亚冠,,无论你是安卓程序员还是广州恒大球迷,欢迎下载代码,或者留下邮箱,我会把Apk发过去
3、统计更新
4、爬虫 >>> Requests 模块
5、php高级


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn