Java———較大二進位檔案的讀、寫

來源:互聯網
上載者:User

標籤:大型   需要   建立檔案   檔案大小   write   個數   false   exception   i++   

  由於項目需要,需要對二進位檔案進行讀寫、轉換。

  檔案說明:由其他程式得到的二進位檔案,檔案內容為:包含23543個三角形、13270個頂點的三角網所對應的721組流速向量(u、v)檔案,通俗些說,一條資料包含兩個雙精確度型的數值,每組數組包含23543條資料,如果以一個雙精確度數值為單位,則總共有23543 * 721 * 2 =33,949,006條資料。由Fortran程式以每 8 Byte儲存一個數值的二進位檔案儲存,最終檔案大小為所示:

              

  

   測試:從該檔案讀出資料之後,轉換為十進位,儲存到另一個檔案中。

  

/** * 針對大檔案儲存體,請依次調用beginSave、AddSave、endSave。 *  * @author CK * */public class DataUtil {    DataOutputStream BinaryOut=null;    BufferedWriter TextOut=null;    String FilePath=null;    enum SaveFileType{Text,Binary};    SaveFileType SaveFileType;    /**     * double轉byte[]     *      * @param d     * @return     */    public static byte[] double2Bytes(double d) {        long value = Double.doubleToRawLongBits(d);        byte[] byteRet = new byte[8];        for (int i = 0; i < 8; i++) {            byteRet[i] = (byte) ((value >> 8 * i) & 0xff);        }        return byteRet;    }    /**     * byte[]轉double     *      * @param arr     * @return     */    public static double bytes2Double(byte[] arr) {        long value = 0;        for (int i = 0; i < 8; i++) {            value |= ((long) (arr[i] & 0xff)) << (8 * i);        }        return Double.longBitsToDouble(value);    }    /**     * 大型資料存放區之開始儲存     * @param FilePath 檔案路徑     * @param saveFileType 儲存的檔案類型,文字檔、雙精確度所存的二進位檔案     * @return     * @throws IOException     */    public boolean BeginSave(String FilePath,SaveFileType saveFileType) throws IOException {        if (FilePath == "" || FilePath == null) {            System.out.println("the SavePath is null.");            return false;        }        this.FilePath=FilePath;        this.SaveFileType=saveFileType;        File dataFile = new File(FilePath);        if (!dataFile.getParentFile().exists()) {            dataFile.getParentFile().mkdirs();        }        if (dataFile.exists()) {            dataFile.delete();        }        dataFile.createNewFile();        switch(this.SaveFileType){        case Text:            TextOut=  new BufferedWriter(new FileWriter(dataFile,true));            break;        case Binary:            BinaryOut = new DataOutputStream(new FileOutputStream(dataFile,true));            break;        default:            break;                    }                return true;    }/** * 大型檔案儲存體之追加儲存 * @param DataStr  若是文本儲存則無要求,若是雙精確度的二進位檔案,以若干空格隔開 * @return * @throws IOException */    public boolean AddSave(String DataStr) throws IOException{        switch(this.SaveFileType){        case Text:            this.TextOut.append(DataStr);            break;        case Binary:            DataStr=DataStr.trim();            String[] dataArray=DataStr.split("\\s+");            for(int i=0;i<dataArray.length;i++){                this.BinaryOut.write(double2Bytes(Double.parseDouble(dataArray[i])));            }                                break;        default:            break;                }                return true;    }    /**     * 大型檔案儲存體之結束儲存,清空緩衝、關閉檔案。     * @return     * @throws IOException     */    public boolean EndSave() throws IOException{        switch(this.SaveFileType){        case Text:            this.TextOut.flush();            this.TextOut.close();            break;        case Binary:            this.BinaryOut.flush();            this.BinaryOut.close();            break;        default:            break;                }                return true;    }  /**     * 將字串儲存為文字檔(一次完成)     *      * @param DataStr     *            檔案內容     * @param SavePath     *            檔案路徑,包含檔案名稱、尾碼     * @return     * @throws IOException     */    public boolean saveTextFile(String DataStr, String SavePath)            throws IOException {        if (DataStr == "" || DataStr == null) {            System.out.println("the dataStr is null.");            return false;        }        if (SavePath == "" || SavePath == null) {            System.out.println("the SavePath is null.");            return false;        }        File dataFile = new File(SavePath);        if (!dataFile.getParentFile().exists()) {            dataFile.getParentFile().mkdirs();        }        if (dataFile.exists()) {            dataFile.delete();        }        dataFile.createNewFile();        BufferedWriter out;        out = new BufferedWriter(new FileWriter(dataFile));        out.append(DataStr);        out.flush();        out.close();        return true;    }    /**     * 雙精確度存為位元據(一次儲存)     *      * @param DataStr  雙精確度資料群組成的字串,以若干空格隔開     * @param OutputPath     * @return     * @throws IOException     */    public boolean saveBinaryFile(String DataStr, String OutputPath) throws IOException {        if (DataStr == "" || DataStr == null) {            System.out.println("the dataStr is null.");            return false;        }        if (OutputPath == "" || OutputPath == null) {            System.out.println("the OutputPath is null.");            return false;        }        File dataFile = new File(OutputPath);        if (!dataFile.getParentFile().exists()) {            dataFile.getParentFile().mkdirs();        }        if (dataFile.exists()) {            dataFile.delete();        }        dataFile.createNewFile();        DataOutputStream out;        out = new DataOutputStream(new FileOutputStream(dataFile));        // 資料處理        DataStr=DataStr.trim();        String[] dataArray=DataStr.split("\\s+");        for(int i=0;i<dataArray.length;i++){            out.write(double2Bytes(Double.parseDouble(dataArray[i])));        }                out.flush();        out.close();        return true;    }}

  代碼說明:其中byte[]與double互轉為在互連網上查到的方法,具體是哪位大神的我忘記了,在這裡為了記錄就貼出來啦,上述程式碼封裝含了處理小型檔案時,將所有內容存在緩衝中,之後再一次性寫入文字檔、二進位檔案中的方法,還包含了對較大型檔案的讀寫方法,下面是自己的一個讀寫測試。

/** * 測試二進位大檔案讀寫(200M左右) * @author ck * */public class FileTest {    static String inputFilePath="";  //輸入檔案路徑,包含檔案名稱尾碼    static String outputFilePath=""; //輸出檔案名,包含檔案名稱尾碼        public static void  file2file() throws IOException{        DataUtil dataUtil=new DataUtil();          DataInputStream br=new DataInputStream(                   new BufferedInputStream(                   new FileInputStream(inputFilePath)));                  dataUtil.BeginSave(outputFilePath, SaveFileType.Text); //初始化,建立檔案,採用檔案追加儲存的思路                 byte[] oneData=new byte[8];                 int i=0,count =0 ;                while(br.read(oneData, 0, 8)!=-1){                        i=i+1;                    dataUtil.AddSave(String.valueOf(DataUtil.bytes2Double(oneData)));                                        if(i/23543==0){                        count++;                        System.out.println(count+"\n");                    }                }                dataUtil.EndSave();       //將還在緩衝中的資料寫入到檔案中,關閉檔案。     }}

 此次測試代碼很快就run完了,但是輸出檔案的產生大概用了近半分鐘(刻意秒錶計時了一次),嘗試用一次性讀寫的辦法,卡很久,也沒有出結果。所得的十進位文字檔,大小為這麼多:

  我想,原來Fortran程式作者的初衷應該是覺得二進位儲存比十進位節省空間的吧,事實上也確實節省了一半多的空間。

  恩,此次記錄完畢。

 

Java———較大二進位檔案的讀、寫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.