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)
    {
        System.out.println("read_file():strFile_name=["+strFile_name+"]");

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

            FileInputStream input=newFileInputStream(strFile_name);

            while((iLenh=input.read(buf))!=-1){
//              ↓ With this process, index over falls.
//              strRead_data+ = new String(buf, "UTF-8").substring(0, iLength);

                String strBuf = new String(buf, "UTF-8");
                System.out.println("iLengh=["+iLengh+"]");
                System.out.println("strBuf=["+strBuf+"]");
                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);
            }

            input.close();

            return strRead_data;
        }
        catch(Exceptione){
            e.printStackTrace();
        }
        return null;
    }

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

File Contents: "1234567890ab"

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

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

java

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.