-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.

3
  • 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. Commented Dec 2, 2015 at 22:55
  • show us what you have done so far. Commented Dec 2, 2015 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. Commented Dec 2, 2015 at 23:18

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

This only works with smaller files.
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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.