我有一个包含很多字节的十六进制文件,我需要根据特定的字节拆分这些字节,例如
f0 1 5 0 0 0 0 0 0 b7 7a 7a e5 db 40 2 0 c0 0 0 9 18 16 0 e3 1 40 0 0 3f 20 f0 1 5 0 0 0 0 0 0 41 bc 7a e5 db 40 2 0 c0 1 0 9 18 16 0 e3 1 40 0 0 3f 20 f0 1 5 0 0 0 0 0 0 53 3f 7b e5 db 40 2 0 c0 3 0 9 2 19 24 3d 0 22 68 1 db 9
当我看到“f0”时,我想拆分字节并存储它们,就像这样
f0 1 5 0 0 0 0 0 0 b7 7a 7a e5 db 40 2 0 c0 0 0 9 18 16 0 e3 1 40 0 0 3f 20
f0 1 5 0 0 0 0 0 0 41 bc 7a e5 db 40 2 0 c0 1 0 9 18 16 0 e3 1 40 0 0 3f 20
f0 1 5 0 0 0 0 0 0 53 3f 7b e5 db 40 2 0 c0 3 0 9 2 19 24 3d 0 22 68 1 db 9
对于其中的每一个,我都希望将其视为一个字符数组来执行一些字符串操作。
如何存储这些模式以及如何将其视为字符来执行操作。
这是我尝试做的事情
String filename = "C:\\tm09888.123";
FileInputStream in = null;
int readHexFile = 0;
char hexToChar = ' ';
String[] bytes = new String[10];
try
{
in = new FileInputStream(filename);
while((readHexFile = in.read()) != -1)
{
if (Integer.toHexString(readHexFile).equals("f0"))
{
System.out.print("\n\n\n");
}
System.out.print(Integer.toHexString(readHexFile) + " ");
}
}
catch (IOException ex)
{
Logger.getLogger(NARSSTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
我成功地拆分了模式,但我如何存储它并对它们中的每一个进行字符串操作
最佳答案
如果文件是二进制文件,您可以将其打印为一系列十六进制数
BufferedInputStream in = new BufferedInputStream(new FileInputStream());
try {
boolean first = true;
for(int b; (b = in.read()) >= 0;) {
if (b == 0xF0 && !first)
System.out.println();
first = false;
System.out.printf("%x ", b);
}
} finally {
in.close();
System.out.println();
}
如果文件是十六进制的文本你可以这样做
String text = FileUtils.readFileAsString(file, "iso-8859-1");
text = text.replaceAll(" f0", "\nf0");
FileUtils.writeStringToFile(file2, text);
或者将其分解成你可以做的几行
String text = FileUtils.readFileAsString(file, "iso-8859-1");
BufferedReader br = new BufferedReader(new StringReader(text.replaceAll(" f0", "\nf0")));
for(String line; (line = br.readLine()) != null;) {
// process one line
}
使用 FileUtils或者你自己的方法来做类似的事情。
关于java - 用java对十六进制文件进行字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13726283/