-1

I am writing a Java program which encrypts a given text using RSA, and saves the encrypted bytes(byte[] array) in a .txt file. There is a separate decryption program which reads these bytes. Now I want to read the same bytes into a byte[] in to the decryption program. How can this be done using Java?

BufferedReader brip = new BufferedReader(new FileReader("encrypted.txt"));
Strings CurrentLine = brip.readLine();
byte[] b = sCurrentLine.getBytes();

This is how I have been reading the data from the file. But it's wrong because it converts the bytes in sCurrentLine variable into again bytes.

user207421
  • 305,947
  • 44
  • 307
  • 483
daipayan
  • 319
  • 3
  • 5
  • 17
  • 3
    Have you tried anything to read it yet? Please demonstrate some attempt at solving your problem by showing example code. If you don't know where to start, Google is always a good bet. – rmlan Dec 02 '15 at 22:55
  • show us what you have done so far. – Raf Dec 02 '15 at 22:57
  • 1
    Everything is wrong here. Encrypted data is not text; shouldn't be stored in a file named .txt; doesn't contain lines; and can't be read with a `Reader.` Use an `InputStream.` – user207421 Dec 02 '15 at 23:18

2 Answers2

29

In Java 7 you can use the readAllBytes() method of Files class. See below:

Path fileLocation = Paths.get("C:\\test_java\\file.txt");
byte[] data = Files.readAllBytes(fileLocation);

There are many other ways to do it see here and here

Der_Meister
  • 4,771
  • 2
  • 46
  • 53
Raf
  • 7,505
  • 1
  • 42
  • 59
1

This code worked for me, in an android project so hopefully, it will work for you.

 private byte[] getByte(String path) {
    byte[] getBytes = {};
    try {
        File file = new File(path);
        getBytes = new byte[(int) file.length()];
        InputStream is = new FileInputStream(file);
        is.read(getBytes);
        is.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return getBytes;
}
Shahzad Afridi
  • 2,058
  • 26
  • 24