1. 程式人生 > >Java讀取二進制文件的方式

Java讀取二進制文件的方式

cat 名稱 close clas generated read tst exist ads

  1. public static void readFile(String fileName){
  2. File file = new File(fileName);
  3. if(file.exists()){
  4. try {
  5. FileInputStream in = new FileInputStream(file);
  6. DataInputStream dis=new DataInputStream(in);
  7. byte[] itemBuf = new byte[20];
  8. //市場編碼
  9. dis.read(itemBuf, 0, 8);
  10. String marketID =new String(itemBuf,0,8);
  11. //市場名稱
  12. dis.read(itemBuf, 0, 20);//read方法讀取一定長度之後,被讀取的數據就從流中去掉了,所以下次讀取仍然從 0開始
  13. String marketName =new String(itemBuf,0,20);
  14. //上一交易日日期
  15. dis.read(itemBuf, 0, 8);
  16. String lastTradingDay = new String(itemBuf,0,8);
  17. //當前交易日日期
  18. dis.read(itemBuf, 0, 8);
  19. String curTradingDay = new String(itemBuf,0,8);
  20. //交易狀態
  21. dis.read(itemBuf, 0, 1);
  22. String marketStatus = new String(itemBuf,0,1);
  23. //交易時段數
  24. short tradePeriodNum = dis.readShort();
  25. System.out.println("市場代碼:"+ marketID);
  26. System.out.println("市場名稱:"+ marketName);
  27. System.out.println("上一交易日日期:"+ lastTradingDay);
  28. System.out.println("當前交易日日期:"+ curTradingDay);
  29. System.out.println("當前交易日日期:"+ curTradingDay);
  30. System.out.println("交易狀態:"+ marketStatus);
  31. System.out.println("交易時段數:"+ tradePeriodNum);
  32. } catch (IOException e) {
  33. // TODO Auto-generated catch block
  34. e.printStackTrace();
  35. }finally{
  36. //close
  37. }
  38. }
  39. }

/** * 隨機讀取文件內容 */ public static void readFileByRandomAccess(String fileName) { RandomAccessFile randomFile = null; try { System.out.println("隨機讀取一段文件內容:"); // 打開一個隨機訪問文件流,按只讀方式 randomFile = new RandomAccessFile(fileName, "r"); // 文件長度,字節數 long fileLength = randomFile.length(); // 讀文件的起始位置 int beginIndex = (fileLength > 4) ? 4 : 0; // 將讀文件的開始位置移到beginIndex位置。 randomFile.seek(beginIndex); byte[] bytes = new byte[10]; int byteread = 0; // 一次讀10個字節,如果文件內容不足10個字節,則讀剩下的字節。 // 將一次讀取的字節數賦給byteread while ((byteread = randomFile.read(bytes)) != -1) { System.out.write(bytes, 0, byteread); } } catch (IOException e) { e.printStackTrace(); } finally { if (randomFile != null) { try { randomFile.close(); } catch (IOException e1) { } } } }

Java讀取二進制文件的方式