由于我遇到的问题,我正在努力解决这个概念。我编写了一种压缩算法,该算法根据存储在数组中的对象中的字符到代码对列表来压缩文本文件。现在,在解压缩时,我意识到我必须逐个字符地读取每个文件,直到创建与其中一个代码匹配的字符串,写入该代码对应的字符,并继续迭代文件直到完成。
我不太确定从这里到哪里去,但这是我到目前为止所拥有的:
CompressedFile compFile = new CompressedFile(args[0],"read");
TextFile outFile = new TextFile(args[0].substring(0,args[0].lastIndexOf('.') )+".dec","write");
String output = "";
String temp = "";
char charac = 0;
check = false;
while(!check) {
charac =compFile.readBit();
if(charac==(char)0) {
throw new NullPointerException();
}
temp=compressionCodes.getCharacter((compressionCodes.findCode(charac)));
还有很多东西缺失,但它不应该真正重要,这只是我真正在努力解决的这个循环。
最佳答案
这是我拥有的一个完整程序示例,它说明了如何进行匹配。注意:如果您具有查找性能,那么使用数组来存储关联是一个坏主意。但是,如果您必须使用数组,则只需迭代该数组,查找与您的搜索条件匹配的第一个查找关联。
来源
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class OpCodeLookupService {
Pair[] opCodes;
public static final class Pair {
String first;
String second;
public Pair(String first, String second) {
this.first = first;
this.second = second;
}
}
public OpCodeLookupService(Pair[] opCodes) {
this.opCodes = opCodes;
}
public Pair pairLookup(String toLookup) {
for(Pair p : this.opCodes) {
if (p.first.equals(toLookup)) {
return p;
}
}
return null;
}
public String lookup(String filePath) {
try {
// In the comments, you mentioned you cannot use BufferedReader to ingest the file. In this example, I'm showing another way via Scanner which is a very easy to use class for ingesting input streams.
Scanner s = new Scanner(new FileInputStream(filePath));
StringBuilder stringToExamine = new StringBuilder();
while (s.hasNext()) {
String nextString = s.next();
for (char c : nextString.toCharArray()) {
stringToExamine.append(c);
Pair pair = pairLookup(stringToExamine.toString());
if (pair != null) {
return pair.second;
}
}
}
return null; //Indicates string is not found.
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Cannot load file");
}
}
public static void main(String...args) {
final Pair p = new Pair("thisisopcode", "12345");
Pair[] pairs = new Pair[1];
pairs[0] = p;
OpCodeLookupService opService = new OpCodeLookupService(pairs);
System.out.println(opService.lookup("/Users/liuben10/foo.txt"));
}
}
因此给定一个如下所示的文本文件:
“这个 isopcodeklajsdfklajdsfkljadf”,
它会输出:
“12345”
关于java - 如何逐个字符读取文件直到完成特定字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48635114/