0

I need to load bytes from a file using Java. is this right ?

InputStream ips=new FileInputStream(file); 
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);                 
String line;
String cle = "" ;
while ((line=br.readLine())!=null){
   cle+=line
}
---> cle.getBytes()

2 Answers2

7

No, that's definitely not the way to do it:

  • You're converting the bytes into text as you read them from a file
  • You're removing all line-breaks (they're not returned from readLine)
  • You're converting the text back into bytes

You're very likely to lose data this way.

To load bytes you shouldn't be using a Reader at all - just use InputStream. It's very important to understand that binary data and text data aren't the same. Treating either of them as the other is a really bad idea.

If you just want to read all the data from an file I would personally use Guava and its Files class:

byte[] data = Files.toByteArray(file);

Or if you've already got an InputStream, use ByteStreams:

byte[] data = ByteStreams.toByteArray(inputSTream);

This also works with InputSupplier.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I found this `RandomAccessFile f = new RandomAccessFile(file, "r"); byte[] cle = new byte[(int)f.length()]; f.read(cle);` is it okey ? –  May 15 '13 at 16:46
0

I would use java.nio.file.Files.readAllBytes

 byte[] bytes = Files.readAllBytes(Paths.get(path));
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • I found this `RandomAccessFile f = new RandomAccessFile(file, "r"); byte[] cle = new byte[(int)f.length()]; f.read(cle);` is it okey ? –  May 15 '13 at 16:51
  • Not quite. f.read(cle) returns the actual number of bytes it read. You should keep reading until it return -1. – Evgeniy Dorofeev May 15 '13 at 17:00