2

I want to read an entire file into a byte array without newline or carriage return. I get 13,10 also in the byte array. Is there a way to read the entire file without newline or carriage return. I have used the below code:

InputStream in = new FileInputStream(file);
numBytesRead=in.read(result, offset, noBytes);

Is there any other way?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Aavik
  • 967
  • 19
  • 48

1 Answers1

4

As far as I know, you'll have to filter that yourself:

byte[] raw = Files.readAllBytes(file.toPath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (byte b : raw)
    if (b != 10 && b != 13)
        baos.write(b);
byte[] result = baos.toByteArray();
xs0
  • 2,990
  • 17
  • 25
  • Thank you. Is there anything other than 10 & 13 I need to filter, as I am new to process file as bytes. – Aavik Nov 27 '17 at 12:28
  • 1
    I don't know, you didn't provide enough information.. What are you trying to do? – xs0 Nov 27 '17 at 12:29
  • I wanted to replace every 2nd and 3rd bytes in a record(size-160) to space. – Aavik Nov 27 '17 at 13:34
  • private void readInBytes(File file, int byteBlockSize) throws IOException { byte[] raw = Files.readAllBytes(file.toPath()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i = 0; for(byte b: raw) { if (i == 2 || i == 3) b = 32; if (b != 10 && b != 13 ) { i++; } if (i > byteBlockSize) i = 0; baos.write(b); System.out.print(b + ","); } } – Aavik Nov 27 '17 at 13:34
  • So you have a file of records, where each is 160 bytes followed by CR LF? – xs0 Nov 27 '17 at 13:36
  • yes, I have a file of record with 160 bytes and have to replace 2nd and 3rd byte of each record with space. The logic seems to work. One more detail. Is it possible to convert byte to char? – Aavik Nov 27 '17 at 14:18
  • Yes, the easiest way is to use this String constructor: `new String(bytes, StandardCharsets.ISO_8859_1)`.. – xs0 Nov 27 '17 at 14:21
  • Is there a limitation in Files.readAllBytes on the file size? – Aavik Nov 27 '17 at 14:46
  • Yes - 2GB (all arrays in Java are limited to 2^31 elements).. If you have a file that big, you may want to process it record by record.. – xs0 Nov 27 '17 at 15:00