Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java FileInputStream

I am trying to use a FileInputStream to essentially read in a text file, and then output it in a different text file. However, I always get very strange characters when I do this. I'm sure it's some simple mistake I'm making, thanks for any help or pointing me in the right direction. Here's what I've got so far.

    File sendFile = new File(fileName);
    FileInputStream fileIn = new FileInputStream(sendFile);
    byte buf[] = new byte[1024];
    while(fileIn.read(buf) > 0) {
        System.out.println(buf);
    }

The file it is reading from is just a big text file of regular ASCII characters. Whenever I do the system.out.println, however, I get the output [B@a422ede. Any ideas on how to make this work? Thanks

like image 980
user2184598 Avatar asked Sep 22 '26 01:09

user2184598


1 Answers

This happens because you are printing a byte array object itself, rather than printing its content. You should construct a String from the buffer and a length, and print that String instead. The constructor to use for this is

String s = new String(buf, 0, len, charsetName);

Above, len should be the value returned by the call of the read() method. The charsetName should represent the encoding used by the underlying file.

like image 180
Sergey Kalinichenko Avatar answered Sep 23 '26 14:09

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!