当前位置: 首页 > news >正文

文件读,写,拷贝,删除

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

  // 创建临时文件
    private static File getFileFromBytes(byte[] b, String suffix) {
        BufferedOutputStream stream = null;
        File file = null;
        try {
            file = File.createTempFile("pattern", "." + suffix);
            System.out.println("临时文件位置:"+file.getCanonicalPath());
            FileOutputStream fstream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    今天比较清闲,总结下最近遇到的文件操作的方法,以供各位道友及贫道今后使用:

//读取文件

    public static String readFile(File f){
        StringBuffer content= new StringBuffer();
        byte[] b = new byte[1024*1024];
       try {
           InputStream reader = new FileInputStream(f);
            while(reader .read(b) != -1){
                content.append(new String(b,"UTF-8"));
            }
            reader .close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(reader != null){
                try {
                    reader .close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return content.toString().trim();
    }

 

//解决读取文件时出现乱码问题

    public static String readFileByUTF8(File file) {
        StringBuffer content = new StringBuffer();
        try {
            if (file.isFile() && file.exists()) {
                InputStreamReader isreader= new InputStreamReader(
                        new FileInputStream(file), "UTF-8");
                BufferedReader breader = new BufferedReader(isreader);
                String fileLine;
                while ((fileLine= breader.readLine()) != null) {
                    content .append(fileLine+ "\n");
                }
                isreader.close();
            }
        } catch (Exception e) {
            System.out.println("读取文件内容操作出错");
            e.printStackTrace();
        }
        return content .toString();
    }



//写入文件(得到的String内容写入文件中)

public static void writeFile(String content, String filepath) {
        try {
            File file = new File(filepath).getParentFile();
            if (!file .exists()) {
               file .mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(filepath);
            Writer out = new OutputStreamWriter(fos, "UTF-8");
            out.flush();
            out.write(content);
            out.close();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        System.out.println("备份报文:" + filepath);
    }

//写入文件(得到的byte[]内容写入文件中)

    public static void writeFile(byte[] content, String filepath) {
        try {
            File file = new File(filepath).getParentFile();
            if (!file.exists()) {
                file.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(filepath);
            fos.write(content, 0, content.length);
            fos.flush();
            fos.close();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        System.out.println("Write File:" + filepath);
    }



//文件拷贝 把一个文件内容拷贝到另一个中

    public static void copyfile(String readpath, String writepath)
            throws FileNotFoundException, IOException {
        File file = new File(writepath).getParentFile();;
        /*如果该文件为空,则创建文件夹*/
        if (!file.exists()) {
            file.mkdirs();
        }
        FileInputStream fis = new FileInputStream(readpath);
        FileOutputStream fos = new FileOutputStream(writepath);
        int len = 0;
        byte[] b = new byte[1024];
        while ((len = fis.read(b)) != -1) {
            fos.write(b, 0, len);
        }
        fis.close();
        fos.close();
    }

//文件删除

    public static void delFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    delFile(files[i]);
                }
                file.delete();
            }
        } else {
            log.error("Delete File:" + file);
        }
    }

 

转载于:https://my.oschina.net/u/3616084/blog/1802155

相关文章:

  • 神州数码网真解决方案助山西电力信息高速化
  • 大数据正在改变企业决策方式
  • Centos 7 配置tomcat服务器
  • 常用软件测试工具的分析
  • 让git更高效--文末有福利
  • 力争大数据及关联产业规模2020年达300亿元
  • python 操作asdl
  • 美国国防部推出微型RFID芯片,助力电子零件防伪
  • 常见错误及细小知识点锦集
  • 物联网之父:中国将引领物联网技术实现飞跃
  • React v16.3 版本新生命周期函数浅析及升级方案
  • 连接无处不在——2016年中国国际信息通信展带你叩响未来世界的大门
  • 二、Java面向对象(8)_继承思想——继承关系
  • 行业领袖支招网络安全:如何走出“黑暗时代”?
  • 《程序设计与数据结构》第八周学习总结
  • 【跃迁之路】【699天】程序员高效学习方法论探索系列(实验阶段456-2019.1.19)...
  • CEF与代理
  • ES6 ...操作符
  • FineReport中如何实现自动滚屏效果
  • input实现文字超出省略号功能
  • Java程序员幽默爆笑锦集
  • nginx 负载服务器优化
  • vue和cordova项目整合打包,并实现vue调用android的相机的demo
  • 分布式熔断降级平台aegis
  • 使用阿里云发布分布式网站,开发时候应该注意什么?
  • 学习JavaScript数据结构与算法 — 树
  • 应用生命周期终极 DevOps 工具包
  • 这几个编码小技巧将令你 PHP 代码更加简洁
  • 新年再起“裁员潮”,“钢铁侠”马斯克要一举裁掉SpaceX 600余名员工 ...
  • #pragma预处理命令
  • $(document).ready(function(){}), $().ready(function(){})和$(function(){})三者区别
  • (01)ORB-SLAM2源码无死角解析-(56) 闭环线程→计算Sim3:理论推导(1)求解s,t
  • (1)(1.11) SiK Radio v2(一)
  • (1)虚拟机的安装与使用,linux系统安装
  • (附源码)spring boot建达集团公司平台 毕业设计 141538
  • (十)c52学习之旅-定时器实验
  • (转)socket Aio demo
  • .bat批处理(六):替换字符串中匹配的子串
  • .net 7 上传文件踩坑
  • .net core webapi 部署iis_一键部署VS插件:让.NET开发者更幸福
  • .NET/C# 编译期间能确定的相同字符串,在运行期间是相同的实例
  • .Net环境下的缓存技术介绍
  • .Net接口调试与案例
  • .php结尾的域名,【php】php正则截取url中域名后的内容
  • @column注解_MyBatis注解开发 -MyBatis(15)
  • @ConditionalOnProperty注解使用说明
  • [ 渗透测试面试篇 ] 渗透测试面试题大集合(详解)(十)RCE (远程代码/命令执行漏洞)相关面试题
  • [2019/05/17]解决springboot测试List接口时JSON传参异常
  • [C#]手把手教你打造Socket的TCP通讯连接(一)
  • [DEBUG] spring boot-如何处理链接中的空格等特殊字符
  • [Excel VBA]单元格区域引用方式的小结
  • [HNOI2015]实验比较
  • [leetcode]114. Flatten Binary Tree to Linked List由二叉树构建链表
  • [Python] 集合操作及方法总结
  • [QJS xmake] 非常简单地在Windows下编译QuickJS!