读写文件io流

欣喜 Java经验 发布时间:2024-01-19 17:28:13 阅读数:1560 1
下文笔者讲述java中IO读写的代码测试,如下所示
@Test
    public void FileOutTest() {
        String filePath="D:/test123.jpeg";
        String toPath="D:/test456.png";
        FileInputStream fis=null;
        FileOutputStream fos=null;
        try {
            fis=new FileInputStream(filePath);
            fos=new FileOutputStream(toPath);
            byte[] bytes=new byte[1024];
            while (true){
                int len = fis.read(bytes);
                if(len!=-1){
                    fos.write(bytes,0,len);
                }else{
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(fis!=null){
                    fis.close();
                }
                if(fos!=null){
                    fos.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }
 

新版IO处理

  @Test
    public void FileCache() {
        try {
            FileChannel fis = new FileInputStream(filePath).getChannel();
            FileChannel fos = new FileOutputStream(toPath).getChannel();
            ByteBuffer bb = ByteBuffer.allocate(1024 * 1024);
            while (true) {
                int read = fis.read(bb);
                if (read == -1) {
                    break;
                }
                bb.flip();
                fos.write(bb);
                bb.clear();
            }
            fis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202401/17056565187712.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者