我的输出反映了我需要处理成十六进制值的文件,但我的十六进制值没有反映在输出中。为什么我的文件不能转换为十六进制值?
public class HexUtilityDump {
public static void main(String[] args) {
FileReader myFileReader = null;
try {
myFileReader = new FileReader("src/hexUtility/test.txt");
} catch(Exception ex) {
System.out.println("Error opening file: " + ex.getLocalizedMessage());
}
BufferedReader b = null;
b = new BufferedReader(myFileReader);
//Loop through all the records in the file and print them on the console
while (true){
String myLine;
try {
myLine = b.readLine();
//check for null returned from readLine() and exit loop if so.
if (myLine ==null){break;}
System.out.println(myLine);
} catch (IOException e) {
e.printStackTrace();
//it is time to exit the while loop
break;
}
}
}
以下是通过转化拉取文件的代码
public static void convertToHex(PrintStream out, File myFileReader) throws IOException {
InputStream is = new FileInputStream(myFileReader);
int bytesCounter =0;
int value = 0;
StringBuilder sbHex = new StringBuilder();
StringBuilder sbText = new StringBuilder();
StringBuilder sbResult = new StringBuilder();
while ((value = is.read()) != -1) {
//convert to hex value with "X" formatter
sbHex.append(String.format("%02X ", value));
//If the character is not convertible, just print a dot symbol "."
if (!Character.isISOControl(value)) {
sbText.append((char)value);
} else {
sbText.append(".");
}
//if 16 bytes are read, reset the counter,
//clear the StringBuilder for formatting purpose only.
if(bytesCounter==15) {
sbResult.append(sbHex).append(" ").append(sbText).append("\n");
sbHex.setLength(0);
sbText.setLength(0);
bytesCounter=0;
}else{
bytesCounter++;
}
}
//if still got content
if(bytesCounter!=0){
//add spaces more formatting purpose only
for(; bytesCounter<16; bytesCounter++){
//1 character 3 spaces
sbHex.append(" ");
}
sbResult.append(sbHex).append(" ").append(sbText).append("\n");
}
out.print(sbResult);
is.close();
}
答案 0 :(得分:1)
您永远不会致电convertToHex
,删除main()
方法中的文件读取。看起来你想做点什么,
File f = new File("src/hexUtility/test.txt");
convertToHex(System.out, f);