【发布时间】:2014-03-20 10:37:23
【问题描述】:
我的想法是制作一个小软件来读取文件(不能“自然”读取,但它包含一些图像),将其数据转换为十六进制,查找 PNG 块(一种标记位于 .png 文件的开头和结尾),并将生成的数据保存在不同的文件中(从十六进制取回后)。我在 Java 中这样做,使用这样的代码:
// out is where to show the result and file is the source
public static void hexDump(PrintStream out, File file) throws IOException {
InputStream is = new FileInputStream(file);
StringBuffer Buffer = new StringBuffer();
while (is.available() > 0) {
StringBuilder sb1 = new StringBuilder();
for (int j = 0; j < 16; j++) {
if (is.available() > 0) {
int value = (int) is.read();
// transform the current data into hex
sb1.append(String.format("%02X ", value));
}
}
Buffer.append(sb1);
// Should I look for the PNG here? I'm not sure
}
is.close();
// Print the result in out (that may be the console or a file)
out.print(Buffer);
}
我确信在打开大文件时还有其他方法可以使用更少的“机器资源”来做到这一点。如果您有任何想法,请告诉我。谢谢!
这是我第一次发帖,如有错误,请帮我更正。
【问题讨论】:
-
您的实际问题是什么?此外,过早的优化是万恶之源——先编写可维护的代码,然后再优化。
-
@Smutje 问题是我在大文件上试过这个,将十六进制数据复制到输出文件需要很长时间。关于可维护的代码,我应该在这里改进什么?我是 Java 编程的新手
-
为什么要将整个文件转换为十六进制?如果您知道十六进制的 PNG 标记,则将其转换为二进制,以便您可以直接将其与文件进行比较。