Mkey
Mkey

Reputation: 163

Java how to read from randomaccessfile into string?

I have a randomaccess file that stores name, address, city, state, and zipcode.

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?

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? Basically I want to know how to read N bytes into a string that can be displayed in a textbox later.


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)

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

Upvotes: 1

Views: 5731

Answers (1)

Klitos Kyriacou
Klitos Kyriacou

Reputation: 11631

The javadoc has your answer. readUTF is meant to be used only for strings that have been previously written to the file using 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).

Upvotes: 1

Related Questions