0

I have a text file which has 16 ASCII characters from positions 9 to 24 in a Mapped File.

Text File

I am trying to retrieve that text into a String variable.

I have tried:

        // MAPPED FILE DATA
        private RandomAccessFile file;
        private static int fileSize = Integer.MAX_VALUE;
        MappedByteBuffer fileBuffer;

        // OPEN MAPPED MEMORY FILE
        file = new RandomAccessFile("myfile.txt", "rw");

        // ASSIGN BUFFER
        fileBuffer = file.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, fileSize);

        // READ HEADER
        byte[] byteExchange = new byte[16]; 
        fileBuffer.position(8);
        fileBuffer.get(byteExchange, 0, 16);

        System.out.print("### ");
        System.out.println(byteExchange);
        System.out.println(byteExchange.toString());
        System.out.println(byteExchange[0]);

But I get this:

### [B@65ab7765
[B@65ab7765
67

While I was expecting

### CME
CME
67

It seems that the individual bytes are being retrieved correctly but I am failing to understand how to convert the byte array into a valid String.

My goal is to have a string variable containing up to 16 characters read from the file (just "CME" in this example).

string myString;
myString = whatever(byteExchange);
System.out.println(myString)

Outputs:

CME
M.E.
  • 4,955
  • 4
  • 49
  • 128
  • 1
    Use `new String(byteExchange, StandardCharsets.US_ASCII);` (if the bytes **really** are 7-bit `ASCII`, otherwise use the [correct encoding](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/StandardCharsets.html#US_ASCII)). – Kayaman Mar 21 '20 at 15:24
  • @Kayaman that solves the problem, thanks – M.E. Mar 21 '20 at 15:26

0 Answers0