0

I want to read a text file, convert it into a byte array, process the byte array and then write it into another file. To do so I don't want to lose any newline characters so that new lines shall also be written into the new file created in the previous step. This is what I have done so far:

StringBuilder line=null;
            try (BufferedReader in = new BufferedReader(new FileReader(filePath))) {
                line = new StringBuilder();
                String tempLine=null;
                fileSelect=true;
                while ((tempLine=in.readLine()) != null) {                      
                    line.append(tempLine+System.lineSeparator());
                }
            }

          byte[] plaintext =String.valueOf(line).getBytes("UTF-8");

    // Encrypt the data
          byte[] encrypted = cipher.doFinal(plaintext);
          //String enc=new String(encrypted);

          try (FileOutputStream out = new FileOutputStream(fileName)) {
                out.write(encrypted);
            }

Take filePath and fileName as valid identifiers in the above code snippet.

2
  • you can also try "%n" Commented Mar 28, 2014 at 8:33
  • Do you want to encrypt every line in the file seperatly, except newline characters? Commented Mar 28, 2014 at 8:44

2 Answers 2

2

I do not understand why you do convert the string, composed using the StringBuilder, into a byte array, but nevertheless, try this code:

String text = "hallo!\n" + "How do\n" + "you do?\n";
System.out.println("Before conversion:");
System.out.print(text);
ByteArrayInputStream is = new ByteArrayInputStream(text.getBytes(Charset.forName("UTF-8")));
StringBuilder builder = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(is))) {
    String line;
    while ((line = in.readLine()) != null) builder.append(line + lineSeparator());
}
byte[] bytes = builder.toString().getBytes(Charset.forName("UTF-8"));
System.out.println("After conversion:");
System.out.print(new String(bytes, "UTF-8"));

OUTPUT:

Before conversion:
hallo!
How do
you do?

After conversion:
hallo!
How do
you do?
Sign up to request clarification or add additional context in comments.

3 Comments

I want to write that into a file and not just print it on the console. In your case, I want 'line' to be written into a text file(say) with all the new lines on their appropriate positions. @harmlezz
my code is an example how to do it. I use the console but you may do exactly the same for your file. Just use the proper encoding as I did in each step. Shouldn't be to hard for you now, right?
yeah, hope so. But I am getting problem only with writing onto the file. Will turn up if I still face the same problem using ByteArrayOutputStream for writing into the file. - @harmlezz
0

it makes no sense write encrypted lines directly as bytes and use CRLF as separator, because CRLF is a legit byte sequence for encrypted data.

you also need to encode every single encrypted line in a compatible format, such as Base64:

public static void main(String[] args) throws IOException
{
    File source = new File("path/to/source/file");
    File target = new File("path/to/target/file");

    List<String> lines = FileUtils.readLines(source, "UTF-8");

    for(String line : lines)
    {
        byte[] encrypted = someEncryptionMethod(line.getBytes("UTF-8"));

        String base64 = Base64.encodeBase64String(encrypted);

        FileUtils.write(target, base64 + "\r\n", true);
    }

}

UPDATE

based only on what you are asking, this is what you should expect:

File source = new File("path/to/source/file");
File target = new File("path/to/target/file");

byte[] bytes = FileUtils.readFileToByteArray(source);

byte[] bytes2 = process(bytes);

FileUtils.writeByteArrayToFile(target, bytes2);

8 Comments

I am implementing CBC in Java and in CBC you need to have entire plaintext message and then fed them to appropriate library function to process for encryption. @michele
-1, this is not what your question states. Correct your question and i'll remove downvote, and try to answer if i can.
My question is just about file handling and nothing more or less than that. I am not talking about encryption or any thing whatsoever. -@michele
ok edited my answer (edit your question anyway because i can't remove downvote otherwise)
I dont understand why you sticking with the encryption thing. Encryption doesn't matters at all here, why should I edit my question? My question says what I want to do. I don't want anybody here to care for what encryption/decryption I use. -@michele
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.