Java讀取二進制文件的方式
阿新 • • 發佈:2018-07-09
cat 名稱 close clas generated read tst exist ads
- public static void readFile(String fileName){
- File file = new File(fileName);
- if(file.exists()){
- try {
- FileInputStream in = new FileInputStream(file);
- DataInputStream dis=new DataInputStream(in);
- byte[] itemBuf = new byte[20];
- //市場編碼
- dis.read(itemBuf, 0, 8);
- String marketID =new String(itemBuf,0,8);
- //市場名稱
- dis.read(itemBuf, 0, 20);//read方法讀取一定長度之後,被讀取的數據就從流中去掉了,所以下次讀取仍然從 0開始
- String marketName =new String(itemBuf,0,20);
- //上一交易日日期
- dis.read(itemBuf, 0, 8);
- String lastTradingDay = new String(itemBuf,0,8);
- //當前交易日日期
- dis.read(itemBuf, 0, 8);
- String curTradingDay = new String(itemBuf,0,8);
- //交易狀態
- dis.read(itemBuf, 0, 1);
- String marketStatus = new String(itemBuf,0,1);
- //交易時段數
- short tradePeriodNum = dis.readShort();
- System.out.println("市場代碼:"+ marketID);
- System.out.println("市場名稱:"+ marketName);
- System.out.println("上一交易日日期:"+ lastTradingDay);
- System.out.println("當前交易日日期:"+ curTradingDay);
- System.out.println("當前交易日日期:"+ curTradingDay);
- System.out.println("交易狀態:"+ marketStatus);
- System.out.println("交易時段數:"+ tradePeriodNum);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- //close
- }
- }
- }
/**
* 隨機讀取文件內容
*/
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讀取二進制文件的方式