【发布时间】:2016-03-10 22:02:12
【问题描述】:
我需要在文件中搜索单词“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"
该代码对我来说很有意义,并且确实看起来应该可以工作,但我没有任何运气。
【问题讨论】:
-
您遇到的错误有时比代码墙更重要。
-
这个代码会得到一个
ArrayIndexOutOfBoundsException.Strange,你没有提到。真是莫名其妙。 -
我已经更新了问题。但是对于 EJP 没有数组问题,先生。无论如何谢谢:)
标签: java binary byte fileinputstream fileoutputstream