我创建了一个霍夫曼编码算法,然后我编写了二进制代码String
并使用FileOutputStream
和将其放入二进制文件中DataOutputStream
。
但是现在我无法理解如何阅读它?我需要从二进制文件中获取 1 和 0 序列。
没有像这样.readString()
的方法DataInputStream
try{
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Binary", "*.bin"));
FileOutputStream fileOutputStream = new FileOutputStream(fileChooser.showSaveDialog(window));
DataOutputStream outputStream = new DataOutputStream(fileOutputStream);
outputStream.writeChars(Main.string_ready_encode);
}catch (IOException e){
e.printStackTrace();
}
Main.string_ready_encode
包含就绪序列
您编写代码的问题在于您没有指定文件格式。我们现在只能读取文件,如果我们知道它有多少字节。如果您知道这一点,您可以通过执行以下操作来阅读它:
try (DataInputStream stream = new DataInputStream(new FileInputStream(f))) {
byte[] bytes = new byte[NUMBER_OF_BYTES];
stream.read(bytes);
String content = new String(bytes);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
但我实际上建议你用一些已知的文件格式重写你的文件,如下所示:
try (Writer writer = new OutputStreamWriter(new FileOutputStream(f), Charsets.UTF_8)) {
writer.write(Main.stringReadyEncode, 0, Main.stringReadyEncode.length());
} catch (IOException x) {
e.printStackTrace();
}
并像阅读任何其他文件一样阅读它:
try (BufferedReader r = Files.newBufferedReader(f.toPath(), Charsets.UTF_8)) {
String line;
while((line = r.readLine()) != null) {
// do whatever you want with line
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
只需确保替换Charsets.UTF_8
为您在写入文件时使用的任何编码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句