生活随笔
收集整理的這篇文章主要介紹了
java 解析二进制文件保存为txt文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java 解析二進制文件保存為txt文件
本文包含二進制解析,遍歷文件夾下的文件,生成對應得文件夾以及文件,日期轉換的知識點
import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.*;/*
SL 二進制文件解析*/
public class ReadSL {//阻塞隊列線程安全private static BlockingQueue<File> queue = new LinkedBlockingQueue<File>(10000);//線程池private static ExecutorService threadPool = Executors.newFixedThreadPool(2);public static void main(String[] args) throws Exception {//監控線程threadPool.execute(new Runnable() {public void run() {while (true) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}int size = queue.size();System.out.println("還有:" + size + "個元素");threadPool.shutdown();}}});for (int i = 1; i <= 1; i++) {threadPool.execute(new Runnable() {public void run() {while (true) {try {//從隊列中獲取文件File file = queue.take();parseText(file);} catch (Exception e) {e.printStackTrace();}}}});}traverseFolder2("D:\\test");}//字節數組轉單精度public static float bytetofloat(byte[] b) {int accum = 0;accum = accum | (b[0] & 0xff) << 0;accum = accum | (b[1] & 0xff) << 8;accum = accum | (b[2] & 0xff) << 16;accum = accum | (b[3] & 0xff) << 24;float accumf= Float.intBitsToFloat(accum);BigDecimal bd = new BigDecimal(accumf);accumf= bd.setScale(6,BigDecimal.ROUND_HALF_UP).floatValue();return accumf;}//字節數組轉intpublic static int bytetoInt(byte[] b) {int jd = 0;int jd0 = b[0] & 0xff;// 最低位int jd1 = b[1] & 0xff;int jd2 = b[2] & 0xff;int jd3 = b[3] & 0xff;jd3 <<= 24;jd2 <<= 16;jd1 <<= 8;jd = jd0 | jd1 | jd2 | jd3;return jd;}//時間轉換public static String getDate(int t) throws ParseException {SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String historyTime = "1970-01-01 08:00:00";Date date = dateFormat.parse(historyTime);Date newDate = addSeconds(date, t);return dateFormat.format(newDate);}private static Date addSeconds(Date date, int seconds) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.add(Calendar.SECOND, seconds);return calendar.getTime();}public static void traverseFolder2(String path) throws Exception {//空文件夾處理File file = new File(path);if (file.exists()) {File[] files = file.listFiles();if (files.length == 0) {return;} else {for (File file2 : files) {if (file2.isDirectory()) {traverseFolder2(file2.getAbsolutePath());} else {//將文件放入阻塞隊列中queue.put(file2);}}}} else {System.out.println("文件不存在!");}}public static void parseText(File file) throws Exception {String result0 = null;//文件的路徑File infile = new File(file.getAbsolutePath());//文件名稱String name = infile.getName();//路徑String absolutePath = infile.getAbsolutePath();//輸入流InputStream bis = new FileInputStream(infile);//輸出路徑String outPath = "D:\\parseData";//切割文件路徑String[] split = absolutePath.split("\\\\");byte[] b = new byte[1022];int len = 0;int count = 0;//txt文件暫不處理if (infile.getName().substring(name.length() - 4, name.length()).equals(".txt")) {return;} else {String time = "";long historyMillons = 0;String listStr = "";String listStr2="";ArrayList<String> list = new ArrayList<String>();//時間long historyTimeMillins=0;String path1 = "\\" + split[1] + "\\" + split[2] + "\\" + split[3] + "\\" + split[4] + "\\" + split[5] + "\\";outPath = outPath + path1 + infile.getName().substring(0, name.length() - 3) + ".txt";//創建文件createFiles(outPath);//輸出流,追加寫入文件BufferedWriter bw = new BufferedWriter(new FileWriter(outPath,true));//保留小數點后六位數字DecimalFormat format = new DecimalFormat("0.000000");while ((len = bis.read(b)) != -1) {count++;if (count == 1) {//版本號byte[] b1 = { b[1], b[2], b[3], b[4], b[5], b[6],b[7],b[8]};//傳感器類型簡寫byte[] b2 = {b[9], b[10]};//傳感器類型全稱byte[] b3 = {b[12], b[13], b[14], b[15], b[16], b[17], b[18], b[19]};//時間byte[] b4 = {b[20], b[21], b[22], b[23]};//傳感器編號byte[] b5 = {b[25], b[26], b[27], b[28], b[29], b[30], b[31], b[32]};String bbh = new String(b1, "UTF-8");//System.out.println("版本號:" + bbh);String jianXie = new String(b2, "UTF-8");String fullName = new String(b3, "GBK");//時間操作 字節數組轉換long類型long s0 = b4[0] & 0xff;// 最低位long s1 = b4[1] & 0xff;long s2 = b4[2] & 0xff;long s3 = b4[3] & 0xff;s1 <<= 8;s2 <<= 16;s3 <<= 24;historyMillons = s0 | s1 | s2 | s3;time = getDate((int) historyMillons);// System.out.println("采集時間:" + time);String bianHao = new String(b5, "utf-8");// System.out.println("傳感器編號:" + bianHao);//頻率 單精度byte[] b6 = {b[33], b[34], b[35], b[36]};float pinLv = bytetofloat(b6);//采樣精度 32位整型byte[] b7 = {b[37], b[38], b[39], b[40]};int jingDu = bytetoInt(b7);//放大倍數byte[] b8 = {b[41], b[42], b[43], b[44]};int beiShu = bytetoInt(b8);//傳感器靈敏度byte[] b9 = {b[45], b[46], b[47], b[48]};float minGanDu = bytetofloat(b9);//文件頭信息結束標志 $// byte[] b11 = {b[49]};//System.out.println(new String(b11));//文件頭信息result0 = bbh + "\t" + jianXie + "\t" + fullName + "\t" + time + "\t" + bianHao + "\t" + pinLv + "\t" + jingDu + "\t" + beiShu + "\t" + minGanDu + "\t";//System.out.println(b.length);//真正數據部分for (int j = 50; j <= len - 4; j += 4) {byte[] b12 = {b[j], b[j + 1], b[j + 2], b[j + 3]};float cjsj = bytetofloat(b12);String flToStr = String.valueOf(cjsj);//取消科學計數法flToStr= format.format(cjsj);historyTimeMillins=historyMillons * 1000 + 50 * ((j - 50) / 4);flToStr = historyTimeMillins+ " " + flToStr;list.add(flToStr);}b=new byte[102400*10];}else {for (int i = 0; i < len - 3; i+=4) {byte[] b13 = {b[i], b[i + 1], b[i + 2], b[i + 3]};float cjsj = bytetofloat(b13);//取消科學計數法String format1 = format.format(cjsj);format1= historyTimeMillins+ 50 * (i / 4) + " " + format1;//System.out.println("采集數據:" + cjsj);list.add(format1);//listStr2 += flToStr + "\r\n";}}}//文件追加寫入bw.write(result0+"\r\n");//System.out.println(list.size());for (int i =0;i<list.size();i++){//換行寫入bw.write(list.get(i)+"\r\n");}bw.flush();bis.close();bw.close();}}public static void createFiles (String outPath) throws IOException {File outFile = new File(outPath);//輸出路徑File parentFile = outFile.getParentFile();if (!parentFile.exists()) {parentFile.mkdirs();}outFile.createNewFile();}public static void createDir (String outPath){File outFile = new File(outPath);//輸出路徑File parentFile = outFile.getParentFile();if (!parentFile.exists()) {parentFile.mkdirs();}outFile.mkdirs();}}
總結
以上是生活随笔為你收集整理的java 解析二进制文件保存为txt文件的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。