从文件中读取字节Java
我试图解析我的文件,它保留所有数据的二进制形式。如何从偏移量为M的文件中读取N个字节?然后我需要使用new String(myByteArray, "UTF-8");
将其转换为字符串。谢谢!从文件中读取字节Java
下面是一些代码:
File file = new File("my_file.txt");
byte [] myByteArray = new byte [file.lenght];
UPD 1:我看到的答案是不是专用的。我的文件以字节形式保存字符串,例如:当我将字符串“str”放入我的文件中时,它实际上会在我的文件中打印出像[B @ 6e0b ...]这样的无格式。因此我需要再次从这个字节码中获得我的字符串“str”。
UPD 2:
PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(System.getProperty("db.file")), true), "UTF-8")));
Iterator it = storage.entrySet().iterator();//storage is a map<String, String>
while (it.hasNext()){
Map.Entry pairs = (Map.Entry)it.next();
String K = new String(pairs.getKey().toString());
String V = new String(pairs.getValue().toString);
writer.println(K.length() + " " + K.getBytes() + " " + V.length() + " " + V.getBytes());//this is just the format I need to have in file
it.remove();
}
可能里有一些不同的方式来执行:由于它的发现,当我使用的toString()出现的问题?
从Java 7开始,阅读整个文件非常简单 - 只需使用Files.readAllBytes(path)
即可。例如:
Path path = Paths.get("my_file.txt");
byte[] data = Files.readAllBytes(path);
如果您需要更多手动做到这一点,你应该使用FileInputStream
- 你的代码到目前为止分配的数组,但不从文件中读取任何东西。
要只读取文件的部分,您应该看看使用RandomAccessFile
,它允许您寻找任何你想要的地方。请注意,read(byte[])
方法确实是而不是保证一次读取所有请求的数据。你应该循环,直到你阅读完所有你需要的东西,或者使用readFully
。例如:
public static byte[] readPortion(File file, int offset, int length)
throws IOException {
byte[] data = new byte[length];
try (RandomAccessFile raf = new RandomAccessFile(file)) {
raf.seek(offset);
raf.readFully(data);
}
return data;
}
编辑:您的更新说明有关看到文本,如[[email protected]
。这表明你在某个时候在byte[]
上打电话toString()
。不要这样做。相反,你应该使用new String(data, StandardCharsets.UTF_8)
或类似的东西 - 当然选择合适的编码。
这不包括“偏移量为M的N字节”部分。 – 2014-10-07 20:58:44
@FlorianF:加,所以它不 - 我错过了。 – 2014-10-07 20:59:27
我已更新我的问题。 – 2014-10-07 21:02:04
[File to byte \ [\] in Java](http://stackoverflow.com/questions/858980/file-to-byte-in-java) – Alboz 2014-10-07 20:56:53
搜索“Java read binary file”and you应该看到很多例子。也请看“Java文件查找”。 – 2014-10-07 20:57:24
'[B @ 6e0b ...'不是字符串写成字节,它是来自字节数组的'toString'的结果,它包含'[B' - 字节数组; '@'分隔符; '6e0b ...'阵列哈希码的十六进制表示。我们可以看到你用来写入字符串的代码吗? – Pshemo 2014-10-07 21:03:42