jialisoftw

          Java 二進制文件讀寫操作

          代碼如下:

          public static byte bSource;

           public static byte bTarget;

           public static byte colon = ':';

           /**
            * 從二進制文件讀取字節數組
            * 
            * @param sourceFile
            * @return
            * @throws IOException
            */
           public static byte[] readFile(File sourceFile) {

            if (sourceFile.isFile() && sourceFile.exists()) {
             long fileLength = sourceFile.length();
             if (fileLength > 0L) {
              try {
               BufferedInputStream fis = new BufferedInputStream(
                 new FileInputStream(sourceFile));
               byte[] b = new byte[(int) fileLength];
               
               while (fis.read(b) != -1) {
               }

               fis.close();
               fis = null;

               return b;
              } catch (IOException e) {
               e.printStackTrace();
              }

             }
            }
            return null;
           }

           /**
            * 將字節數組讀入二進制文件
            * 
            * @param targetFile
            * @param content
            * @return
            */
           public static boolean writeBytes(File targetFile, byte[] content) {

            try {
             BufferedOutputStream fos = new BufferedOutputStream(
               new FileOutputStream(targetFile));

             for (int i = 0; i < content.length - 1; i++) {
              // 替換掉盤符路徑(E:) 以冒號作為判斷改字節是否代表一個盤符
              if (content[i] == bSource && content[i + 1] == colon) {
               content[i] = bTarget;
              }
              fos.write(content[i]);
             }

             fos.write(content[content.length - 1]); // 寫入最后一個字節

             fos.flush();
             fos.close();

             return true;
            } catch (IOException e) {
             e.printStackTrace();
            }
            return false;
           }

          posted on 2012-10-17 15:30 飛豬一號 閱讀(1689) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          導航

          <2012年10月>
          30123456
          78910111213
          14151617181920
          21222324252627
          28293031123
          45678910

          統計

          常用鏈接

          留言簿

          隨筆檔案

          友情鏈接

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 西吉县| 普兰店市| 曲沃县| 深州市| 镇赉县| 江门市| 博野县| 靖江市| 汝城县| 凤庆县| 霍林郭勒市| 太白县| 临夏县| 永济市| 凉城县| 唐河县| 新宁县| 瑞金市| 临漳县| 巴林右旗| 莫力| 吉隆县| 揭阳市| 沂水县| 巴彦县| 仲巴县| 南靖县| 屯留县| 枣阳市| 五家渠市| 天津市| 贵溪市| 开阳县| 屯留县| 太湖县| 阳东县| 都江堰市| 双江| 昌黎县| 舟曲县| 申扎县|