How Java loads binaries and text files into String

Asked 2 months ago, Updated 2 months ago, 3 views

Java is having trouble loading binaries and text files into String.

What's troubling you? File size statement, repeatedly loading buf size 1024 bytes, but
Finally, it will be less than or equal to the fraction of 1024 bytes.
If you combine the contents of the reading below,

I think I should leave the buf empty every time before loading it.
It doesn't work.

How can I
binary or text files (either way) Should I load it into String?

public String read_file(String strFile_name)

            String strRead_data="";
            byte buf[] = new byte [1024];
            intiLength = 0;

            FileInputStream input=newFileInputStream(strFile_name);

//              ↓ With this process, index over falls.
//              strRead_data+ = new String(buf, "UTF-8").substring(0, iLength);

                String strBuf = new String(buf, "UTF-8");
                strRead_data+=strBuf;// Even if only 50 bytes are read this time, 1024-50 bytes of data previously read are added after 50 bytes.

//              This makes an exception for index over
//              strRead_data+=strBuf.substring(0,iLenh);

// Have you tried emptying the buf??        Arrays.fill(buf, (byte)0);


            return strRead_data;
        return null;

Specific examples:
byte buf[] = new byte[5]; denoted as .

File Contents: "1234567890ab"

read loop:
First time:
Second time:
buf: [ab890] " "890" and previously loaded data are still available.

Originally, I want
at the end. buf: [ab]
That's it.


2022-09-30 14:16

1 Answers

new String (buf, 0, iLength, "UTF-8")

allows you to string data from the 0 byte to the length iLength byte of byte[].

2022-09-30 14:16

If you have any answers or tips

© 2022 OneMinuteCode. All rights reserved.