[英]Java: Searching For Specific Bytes in a binary file and replacing or omitting said bytes
我需要在文件中搜索“test”这个词。 我使用的文件是一个文本文件,但我将在二进制文件上使用它。
下面的代码看起来应该对我有用,但它不起作用。 我能够在文件中显示“test”的实例,但我无法让它基本上不在创建的文件中写入“test”。
请问有什么帮助吗?
public static void makelabels(){
File file = new File("test.txt");
// Check if File Exists.
if(file.exists()){
//Do work boy!!!!
int length = (int) file.length();
System.out.println("\nFile Length is "+length+" bytes");
try{
byte[] bytes = new byte[length];
int i = 0;
int count = 0;
char c;
FileInputStream input = new FileInputStream(file);
FileOutputStream output = new FileOutputStream("test2.txt");
input.read(bytes);
for(byte b:bytes){
c = (char) b;
if(Character.toString(c).equals("t")){
if(Character.toString((char) bytes[i+1]).equals("e")){
if(Character.toString((char) bytes[i+2]).equals("s")){
if(Character.toString((char) bytes[i+3]).equals("t")){
count++;
System.out.println("Found TEST " + count +" times");
}
else{
output.write(b);
}
}
else{
output.write(b);
}
}
else{
output.write(b);
}
}
else{
output.write(b);
}
i++;
}
System.out.println("\n\n");
System.out.println("Test Results\n\n");
input.close();
output.close();
return;}
catch(FileNotFoundException ex){
System.out.println("\nFile Not Found");
}
catch(IOException ex){
System.out.println("\nCan't Read File");
}
}
else{
System.out.println("\nFile Not Found!");
return;
}
}
感谢你们提供的帮助。
我没有遇到数组问题。
这是测试文件的内容。
"this is a test
Please test me"
这是我的结果
"this is a est
Please est me"
代码对我来说很有意义,看起来它应该可以工作,但我没有任何运气。
我可能会建议以不同的方式处理它,而不是将每个人转换为一个字节。
byte[] match = "test".getBytes();
for(int i =0; i < 1 + bytes.length - match.length; i++){
boolean flag = true;
for(int j= 0; j < match.length; j++){
if(match[j] != bytes[i+j]){
flag = false;
break;
}
}
if(flag){
count++;
i+=match.length-1; // don't check these bytes anymore which will also cause them to not be written because it won't do the check below.
}else{
output.write(b);
}
}
外循环将遍历可能开始您想要匹配的字符串的每个字节。 内循环将从起点开始并比较以下字节。 如果所有字节都匹配,则 Flag 将保持为真。 但是,如果存在差异,flag 将设置为 false。 因此,如果 flag 为真,则增加计数。
编辑:如果找到匹配项,上面的代码现在将索引增加您尝试匹配的字符串的长度。 它这样做与写入输出相反。 据我了解,这就是您要问的问题,但我不确定。 如果那不是你想要的,你能再解释一下吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.