简体   繁体   English

Java如何从randomaccessfile读取到字符串?

[英]Java how to read from randomaccessfile into string?

I have a randomaccess file that stores name, address, city, state, and zipcode. 我有一个randomaccess文件,用于存储名称,地址,城市,州和邮政编码。

They are all a fixed size of bytes in the file (each entry). 它们都是文件(每个条目)中字节的固定大小。 How would I read from the file into a string for each item like name, street, etc? 如何从文件中读取名称,街道等每个项目的字符串?

I've tried 我试过了

 string name = raf.readUTF(); 

But I can't control how many bytes it reads will that stop it from working correctly? 但是我无法控制它读取多少字节,这会阻止它正常工作? Or how does readUTF work exactly since no amount of total bytes to read can be supplied in the arguement? 还是因为争论中无法提供要读取的总字节数,所以readUTF到底如何工作?

Or is a better approach to do 还是更好的方法

 ENTRY1_SIZE = 32;
 raf.read(string1);
 raf.skipBytes(ENTRY1_SIZE - string1.size());
 raf.read(string2);

and so on like that. 像这样

What would be the most efficient way to do this while still using a randomaccessfile? 在仍然使用randomaccessfile的情况下,最有效的方法是什么? Basically I want to know how to read N bytes into a string that can be displayed in a textbox later. 基本上,我想知道如何将N个字节读取为一个字符串,以后可以在文本框中显示该字符串。


Response to the answer below. 回应以下答案。 I tried your method 我尝试过你的方法

        long position = 91;
        byte[] b = new byte[32];
        try{
        raf.seek(position);
        raf.readFully(b, position, 32);
        String name = (b, StandardCharsets.UTF_8);

But this error: The method readFully(byte[], int, int) in the type RandomAccessFile is not applicable for the arguments (byte[], long, int) 但是会出现此错误:RandomAccessFile类型的方法readFully(byte [],int,int)不适用于参数(byte [],long,int)

What should be supplied for the middle argument? 中间论证应提供什么? The current file pointer is a long so that wouldn't work either. 当前的文件指针很长,因此也不起作用。

Another error: StandardCharsets cannot be resolved or is not a field 另一个错误:StandardCharsets无法解析或不是字段

The javadoc has your answer. javadoc有您的答案。 readUTF is meant to be used only for strings that have been previously written to the file using writeUTF . readUTF仅适用于以前使用writeUTF写入文件的字符串。 If your file has fixed-length regions, you should use readfully(byte[]) using an appropriately-sized byte array, and then convert the byte array to a string using new String(bytes, StandardCharsets.UTF_8) . 如果文件具有固定长度的区域,则应通过适当大小的字节数组使用readfully(byte []) ,然后使用new String(bytes, StandardCharsets.UTF_8)将字节数组转换为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM