跪求:java读取二进制文件写成十六进制字符串,并把字符串写入txt。我的程序生成了,但却是空的。求解~~~

package erjinzhi;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ReadBinaryTest {
public void testDataInputStream(String filepath) throws IOException {
File file = new File(filepath);
DataInputStream din = new DataInputStream(new FileInputStream(file));
StringBuilder hexData = new StringBuilder();
StringBuilder asciiData = new StringBuilder();
byte temp = 0;
for(int i=0;i<file.length();i++) {
temp = din.readByte();
// 以十六进制的无符号整数形式返回一个字符串表示形式。
String str = Integer.toHexString(temp);
// System.out.println(++i +":" + Integer.toHexString(temp).length() + ":" + Integer.toHexString(temp));
// System.out.flush();
if(str.length() == 8) {//去掉补位的f
str = str.substring(6);
}
if(str.length() == 1) {
str = "0"+str;
}
hexData.append(str.toUpperCase());
//转换成ascii码
String ascii = "";
if(temp>34 && temp <127) {
char c = (char)temp;
ascii = c+"";
}else{
ascii = ".";
}
asciiData.append(ascii);
//System.out.println(str.toUpperCase()+"|"+temp+"|"+ascii);
}
//计算行数
int line = hexData.toString().length()/32;
din.close();
StringBuilder lines = new StringBuilder();
for(int i=0;i<=line;i++) {
String li = i+"0";
if(li.length() == 2){
li = "00"+li;
}
if(li.length() == 3) {
li = "0"+li;
}
lines.append(li);
}
System.out.println(lines.toString());
}
public static void main(String[] args) throws IOException {
String filepath = "C:\\rf\\ccccc.pdf";
ReadBinaryTest test = new ReadBinaryTest();
test.testDataInputStream(filepath);

FileOutputStream fout = new FileOutputStream("c:\\b.txt");//将十六进制数存成文本
fout.close();
}
}

你输入流读进来存在内存中了,但是没往输出流里写啊
FileOutputStream fout = new FileOutputStream("c:\\b.txt");//将十六进制数存成文本
fout.close();
new了一个输出流,然后就关了,加上fout.write(asciiData .getBytes()) 再关吧。追问

我试了,不对啊~~~asciiData处有问题~~~

追答

抱歉,刚没细看,我给调了下,减掉了不必要的冗余功能。

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ReadBinaryTest {
public String testDataInputStream(String filepath) throws IOException {
File file = new File(filepath);
DataInputStream din = new DataInputStream(new FileInputStream(file));
StringBuilder hexData = new StringBuilder();
byte temp = 0;
for(int i=0;i<file.length();i++) {
temp = din.readByte();
// 以十六进制的无符号整数形式返回一个字符串表示形式。
String str = Integer.toHexString(temp);
if(str.length() == 8) {//去掉补位的f
str = str.substring(6);
}
if(str.length() == 1) {
str = "0"+str;
}
hexData.append(str.toUpperCase());
}
return hexData.toString();
}
public static void main(String[] args) throws IOException {
String filepath = "E:\\Nexus Install and Configure.pptx";
ReadBinaryTest test = new ReadBinaryTest();
String s = test.testDataInputStream(filepath);

FileOutputStream fout = new FileOutputStream("E:\\b.txt");//将十六进制数存成文本
fout.write(s.getBytes());
fout.close();
}
}

温馨提示:答案为网友推荐,仅供参考