温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

利用Java读取二进制文件实例详解

发布时间:2020-10-09 22:59:45 来源:脚本之家 阅读:168 作者:RustFisher 栏目:编程语言

前言

本文主要给大家介绍了关于Java读取二进制文件的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

读Hex写CSV

data目录下有little-endian bin文件,2个字节代表一个数字。

bin存储的数据格式可自己定义。相同的方法可以直接应用到Android中。

`-- networkProj
 |-- data
 |-- networkProj.iml
 |-- out
 `-- src

实现方法

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);
}

控制台输出

--------- 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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI