前言
本文主要給大家介紹了關于Java讀取二進制文件的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。
讀Hex寫CSV
data目錄下有little-endian bin文件,2個字節代表一個數字。
bin存儲的數據格式可自己定義。相同的方法可以直接應用到Android中。
1
2
3
4
5
|
`-- networkProj |-- data |-- networkProj.iml |-- out `-- src |
實現方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
private static void convertFiles() { File folder = new File( "data" ); // data folder log( "--------- Read little-endian data from bin file ---------" ); if (!folder.exists()) { log( "folder is not exist!" ); return ; } File outputFolder = new File(folder.getAbsolutePath() + File.separator + "output" ); if (!outputFolder.exists()) { boolean newOutput = outputFolder.mkdir(); log( "New output folder " + newOutput); } File[] files = folder.listFiles(); if (files != null ) { log( "folder is " + folder.getAbsolutePath()); for (File f : files) { log( "\t" + f.getName()); } } else { log( "Nothing in this folder" ); return ; } for (File currentFile : files) { if (!currentFile.isFile()) { return ; } String fileName = currentFile.getName(); fileName = fileName.substring( 0 , fileName.length() - 4 ); // delete suffix File csvFile = new File(outputFolder.getAbsolutePath() + File.separator + fileName + ".csv" ); if (csvFile.exists()) { boolean deRes = csvFile.delete(); log( "Delete old csv: " + deRes); } byte [] readBytes = new byte [ 512 ]; try { boolean newCsv = csvFile.createNewFile(); log(csvFile.getAbsolutePath() + " " + newCsv); FileOutputStream csvFos = new FileOutputStream(csvFile); InputStream in = new FileInputStream(currentFile); while (in.read(readBytes) != - 1 ) { int [] csvData = convertBytesToInts(readBytes); for ( int d : csvData) { csvFos.write(String.valueOf(d).getBytes()); csvFos.write( "\n" .getBytes()); } } csvFos.flush(); csvFos.close(); } catch (Exception e) { e.printStackTrace(); } } } // little-endian; 2 bytes -> 1 int private static int [] convertBytesToInts( byte [] inputData) { int [] rawData = new int [inputData.length / 2 ]; int rawIndex = 0 ; for ( int i = 0 ; i < inputData.length; i += 2 ) { int raw = ( 0xff & inputData[i + 1 ]) * 256 + ( 0xff & inputData[i]); if (raw >= 32768 ) { raw -= 65536 ; } rawData[rawIndex] = raw; rawIndex++; } return rawData; } private static void log(String l) { System.out.println(l); } |
控制臺輸出
1
2
3
4
5
6
|
--------- Read little-endian data from bin file --------- New output folder true folder is G:\javaProj\networkProj\data data20170215_180621.bin output G:\javaProj\networkProj\data\output\data20170215_180621.csv true |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:http://rustfisher.github.io/2017/02/16/Java_note/Java_Read_Hex_write_csv/