利用IO流一次性读取文件中的所有内容,利用IO流下载文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28483283/article/details/81128955

利用IO流一次性读取文件中的所有内容

读取文件效率最快的方法就是一次全读进来,使用readline()之类的方法,可能需要反复访问文件,而且每次readline()都会调用编码转换,降低了速度,所以,在已知编码的情况下,按字节流方式先将文件都读入内存,再一次性编码转换是最快的方式,代码如下:

try {
            File f = ResourceUtils.getFile(AndroidConst.JSON_FILE_PATH+AndroidConst.JSON_FILE_NAME);
            if(!f.exists()) {
                return Result.returnErrorResult("file "+AndroidConst.JSON_FILE_NAME+" not found ."); 
            }

             Long filelength = f.length();  

             byte[] filecontent = new byte[filelength.intValue()];  

             FileInputStream in = new FileInputStream(f);  
             in.read(filecontent);  
             in.close();  

             String content=new String(filecontent);

             JSON json = JSONObject.parseObject(content, JSON.class);

             System.out.println(content); 
             return Result.returnResult(json);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.returnResult("error !");

将读取的文件内容直接转换成 json返回


利用IO流下载文件

同样是使用一次性全部读取的方式,将文件全部读取,并且放入缓存中,然后在写入response中直接返回

package com.huali.business.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

public class DownloadUtil {
    public static HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);

            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }


}

以上是一个工具类,通过response=DownloadUtil.download(AndroidConst.APK_FILE_PATH+fileName, response);直接调用即可!

猜你喜欢

转载自blog.csdn.net/qq_28483283/article/details/81128955