java读写文件,根据指定文件名后缀读写文件夹内文件,删除文件,下载文件

除下载文件外都已测试通过

package com.goldpac.ocs.common.gatewaymanagerservice.service.impl;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class test {

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

            String filepath = "C:\\Users\\jian.li\\Desktop";
            //读写目录下匹配指定格式的文件
            getfile(filepath);

            String pathname = "C:\\Users\\jian.li\\Desktop\\input - 副本.log";
            //删除文件
            delFile(pathname);
        }

        //读取文件
        public static void readFile(String pathname) {
            String text = "";
            //防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw;
            //不关闭文件会导致资源的泄露,读写文件都同理
            //Java7的try-with-resources可以优雅关闭文件,异常时自动关闭文件;详细解读https://stackoverflow.com/a/12665271
            try (FileReader reader = new FileReader(pathname);
                 // 建立一个对象,它把文件内容转成计算机能读懂的语言
                 BufferedReader br = new BufferedReader(reader)
            ) {
                String line;
                // 一次读入一行数据
                while ((line = br.readLine()) != null) {
                    text = text + line + "\r\n";
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(text);
            //组装每次读取的每一行,写入操作
            writeFile(text);
        }

        //写入文件
        public static void writeFile(String line) {
            try {
                // 相对路径,如果没有则会建立一个新的output.log文件
                File writeName = new File("C:\\Users\\jian.li\\Desktop\\output.log");
                writeName.createNewFile(); // 创建新文件,有同名的文件的话直接覆盖
                try (FileWriter writer = new FileWriter(writeName);
                     BufferedWriter out = new BufferedWriter(writer)
                ) {
                    out.write(line);
                    // 把缓存区内容压入文件
                    out.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //读取文件路径(匹配指定文件夹内以.log结尾的文件路径,自己可扩展)
         public static void getfile(String filepath) throws FileNotFoundException, IOException {
        try {

            File file = new File(filepath);
            if (!file.isDirectory()) {
                System.out.println("文件");
                System.out.println("path=" + file.getPath());
                System.out.println("absolutepath=" + file.getAbsolutePath());
                System.out.println("name=" + file.getName());

            } else if (file.isDirectory()) {
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File readfile = new File(filepath + "\\" + filelist[i]);
                    //只输出文件以.log结尾的路径
                    if (!readfile.isDirectory() && "log".equals(readfile.getName().substring(readfile.getName().lastIndexOf(".")+1,readfile.getName().length()))) {
                        System.out.println("path=" + readfile.getPath());
                        System.out.println("absolutepath="
                                + readfile.getAbsolutePath());
                        System.out.println("name=" + readfile.getName());
                        //调用写入方法
                        readFile(readfile.getPath());
                    } else if (readfile.isDirectory()) {
                        getfile(filepath + "\\" + filelist[i]);
                    }
                }

            }

        } catch (FileNotFoundException e) {
            System.out.println("readfile()   Exception:" + e.getMessage());
        }
    }

     //删除文件
     public static boolean delFile(String path) {
        System.out.println("进入deFile方法 psth =: "+path);
        boolean flag = false;
        File file = new File(path);
        System.out.println("操作文件文件,文件列表如下~~__--~~~~~~~~~~~~~~~~~~~:::"+file);
        if (!file.exists()) {
            return flag;
        }
        try{
            flag = file.delete();
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }


    //下载文件 advertis为文件名 file为文件所在路径
    public static void downFile( String advertis,HttpServletResponse response) throws IOException{
            String file = "" + "/"+advertis;
        FileInputStream fileInputStream = new FileInputStream(file);
        //设置Http响应头告诉浏览器下载这个附件,下载的文件名也是在这里设置的
        response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(advertis, "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[2048];
        int len = 0;
        while ((len = fileInputStream.read(bytes))>0){
            outputStream.write(bytes,0,len);
        }
        fileInputStream.close();
        outputStream.close();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值