JAVA文件讀寫方法和性能比較總結


  (本文摘自:http://www.360doc.com/content/13/1218/13/9560593_338124453.shtml)

  

文件讀寫有以下幾種常用的方法

  1. 字節讀寫(InputStream/OutputStream)

  2. 字符讀取(FileReader/FileWriter)

  3. 行讀取(BufferedReader/BufferedWriter)

測試代碼如下:

package com.waddell.basic;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * <b>文件讀取類</b><br />
 * 1、按字節讀取文件內容<br />
 * 2、按字符讀取文件內容<br />
 * 3、按行讀取文件內容<br />
 * 
 * @author qin_xijuan
 * 
 */
public class FileOperate {

    private static final String FILE_PATH = "d:/work/jipinwodi.txt";

    /**
     * 以字節為單位讀寫文件內容
     * 
     * @param filePath
     *            :需要讀取的文件路徑
     */
    public static void readFileByByte(String filePath) {
        File file = new File(filePath);
        // InputStream:此抽象類是表示字節輸入流的所有類的超類。
        InputStream ins = null;
        OutputStream outs = null;
        try {
            // FileInputStream:從文件系統中的某個文件中獲得輸入字節。
            ins = new FileInputStream(file);
            outs = new FileOutputStream("d:/work/readFileByByte.txt");
            int temp;
            // read():從輸入流中讀取數據的下一個字節。
            while ((temp = ins.read()) != -1) {
                outs.write(temp);
            }
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            if (ins != null && outs != null) {
                try {
                    outs.close();
                    ins.close();
                } catch (IOException e) {
                    e.getStackTrace();
                }
            }
        }
    }

    /**
     * 以字符為單位讀寫文件內容
     * 
     * @param filePath
     */
    public static void readFileByCharacter(String filePath) {
        File file = new File(filePath);
        // FileReader:用來讀取字符文件的便捷類。
        FileReader reader = null;
        FileWriter writer = null;
        try {
            reader = new FileReader(file);
            writer = new FileWriter("d:/work/readFileByCharacter.txt");
            int temp;
            while ((temp = reader.read()) != -1) {
                writer.write((char)temp);
            }
        } catch (IOException e) {
            e.getStackTrace();
        } finally {
            if (reader != null && writer != null) {
                try {
                    reader.close();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 以行為單位讀寫文件內容
     * 
     * @param filePath
     */
    public static void readFileByLine(String filePath) {
        File file = new File(filePath);
        // BufferedReader:從字符輸入流中讀取文本,緩沖各個字符,從而實現字符、數組和行的高效讀取。
        BufferedReader bufReader = null;
        BufferedWriter bufWriter = null;
        try {
            // FileReader:用來讀取字符文件的便捷類。
            bufReader = new BufferedReader(new FileReader(file));
            bufWriter = new BufferedWriter(new FileWriter("d:/work/readFileByLine.txt"));
            // buf = new BufferedReader(new InputStreamReader(new
            // FileInputStream(file)));
            String temp = null;
            while ((temp = bufReader.readLine()) != null) {
                bufWriter.write(temp+"\n");
            }
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            if (bufReader != null && bufWriter != null) {
                try {
                    bufReader.close();
                    bufWriter.close();
                } catch (IOException e) {
                    e.getStackTrace();
                }
            }
        }
    }

    /**
     * 使用Java.nio ByteBuffer字節將一個文件輸出至另一文件
     * 
     * @param filePath
     */
    public static void readFileByBybeBuffer(String filePath) {
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            // 獲取源文件和目標文件的輸入輸出流  
            in = new FileInputStream(filePath);
            out = new FileOutputStream("d:/work/readFileByBybeBuffer.txt");
            // 獲取輸入輸出通道
            FileChannel fcIn = in.getChannel();
            FileChannel fcOut = out.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (true) {
                // clear方法重設緩沖區,使它可以接受讀入的數據
                buffer.clear();
                // 從輸入通道中將數據讀到緩沖區
                int r = fcIn.read(buffer);
                if (r == -1) {
                    break;
                }
                // flip方法讓緩沖區可以將新讀入的數據寫入另一個通道  
                buffer.flip();
                fcOut.write(buffer);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null && out != null) {
                try {
                    in.close();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static long getTime(){
        return System.currentTimeMillis();
    }

    public static void main(String args[]) {
        long time1 = getTime() ;
        // readFileByByte(FILE_PATH);// 8734,8281,8000,7781,8047
        // readFileByCharacter(FILE_PATH);// 734, 437, 437, 438, 422
        // readFileByLine(FILE_PATH);// 110, 94,  94,  110, 93
        readFileByBybeBuffer(FILE_PATH);// 125, 78,  62,  78, 62
        long time2 = getTime() ;
        System.out.println(time2-time1);
    }
}

  在main方法中,調用各方法之后,有五組數據,分辨是我5次讀寫文件測試出來的時間(毫秒)。通過讀寫一個1.2M的文本文件來測試各方法的性能。從多次測試結果來看,行讀寫卻是是Java.nio更有效率。

  關於Java.nio 請參考:http://www.iteye.com/topic/834447

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM