0

I have decrypted data in bytearrayoutputstream. I want to read the data in each line(not sure if that is possible).Could any one guide how I can do that.

The main requirement is to read a encrypted file , decrypt and read the data without writing into the disk. I have already covered encrypt and decrypt part but unable to read the data without writing into disk.Some suggested to use bytearrayoutputStream so stuck now.

ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(inputBytes.length);
byteArrayOutputStream.write(outputBytes);

if i simply print the variable it give me all the data at once as below.

SQlServer,"connection string","user name","password"
Oracle,"connection string","user name","password"

I am trying to read the data line wise so i can match the servername and fetch the user name and other details.

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
Shubham Sahay
  • 88
  • 2
  • 12
  • 2
    Possible duplicate of [How to read a large text file line by line using Java?](https://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java) – Alex Shesterov Jan 04 '19 at 12:00
  • have you tried to use `toByteArray`? – Leonardo Alves Machado Jan 04 '19 at 12:03
  • @LeonardoAlvesMachado yes not working...could you suggest if you have a way to use it. – Shubham Sahay Jan 04 '19 at 12:26
  • The proper way would be to not have the `ByteArrayOutputStream` at all, but instead wrap the file input stream in a [`CipherInputStream`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/javax/crypto/CipherInputStream.html) or otherwise a custom `FilterInputStream`, so it is decrypted while being read. There should be no need to read and decrypt the entire file to a byte array and then read it back. – Mark Rotteveel Jan 04 '19 at 12:37
  • @ShubhamSahay I didn't quite understand why you are using an output class (used to write to streams, in your case) in order to read stuff. When I said to use `toByteArray`, I meant to give you the data that it contains, so you could use it in an input class (used to read data) of your choice... If you couldn't get the data from it, you might be able to get it from the variable `outputBytes` in your code. – Leonardo Alves Machado Jan 04 '19 at 12:57
  • @LeonardoAlvesMachado thanks for the suggestion will try and share my again if i find difficulty. – Shubham Sahay Jan 07 '19 at 09:50
  • @MarkRotteveel I was trying this out too, but somehow was not able to do. Will try again – Shubham Sahay Jan 07 '19 at 09:51

1 Answers1

0

To read a byte[] you can use

ByteArrayInputStream in = new ByteArrayInputStream(outputBytes);

and to read this as lines of text you can use

BufferedReader br = new BufferedReader(new InputStreamReader(in));
for (String line; (line = br.readLine()) != null; ) {
    // do something with the line
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130