1. 程式人生 > >利用IO流一次性讀取檔案中的所有內容,利用IO流下載檔案

利用IO流一次性讀取檔案中的所有內容,利用IO流下載檔案

利用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);直接呼叫即可!