调试Java基本十六进制编辑器编程任务
我正在为学校的作业编写一个基本的十六进制编辑器。我只完成了大约90%,但是,我不知道如何将一个新的字节值分配给一个已经存在的字节值。基本上,我会询问用户是否希望在他们指定的位置(代码前面)修改一个字节。如果他们选择“是”,则应提示他们输入新的十六进制值,以覆盖该位置的十六进制值。到目前为止,我有:
System.out.print("Would you like to edit the byte at this position?(y/n): ");
String choice;
choice = in.nextLine();
if ("y".equals(choice)){
System.out.print("Enter the new hex value: ");
String hv = in.nextLine();
int i = Integer.decode("0x" + hv);
在这里,我真的不知道如何将它们输入的值放入相应的位置
下面是设置用户指定位置的前一段代码:
System.out.print("Enter byte positon to navigate to: ");
long loc = in.nextLong(); in.nextLine();
if (loc >= 0 && loc < fileList.size()) {
ListIterator<Byte> lit = fileList.listIterator((loc - 5 >= 0)?(int)(loc-5):0);
int start = lit.nextIndex();
System.out.println("The surrounding 5 bytes (left and right) are: ");
while (start <= loc+5 && start < fileList.size()){
if (start == loc){
System.out.print(" ( ");
}
byte b = lit.next();
System.out.print(((b >= 0 && b <= 15)?"0":" ") + Integer.toHexString((int)b & 0x00FF) + " ");
if (start == loc)
System.out.print(" ) ");
System.out.print(" ");
start++;
}
非常感谢您的帮助。谢谢
# 1 楼答案
如果我理解正确,您的
fileList
包含打开文件的每个字节。这就是至少检索所选字节的方式因此,也许您可以使用
set()
方法来更改fileList
(https://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#set(E))的一个字节我认为您需要转到正确的偏移量,调用
next()
来检索它,然后调用set()
来定义它,如果我正确理解文档的话执行此操作后,字节可能仅在内存中更改,如果要保留它们,则仍需要将其写入磁盘