Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ArrayList<String> to byte[]

I want to be able to convert an ArrayList<String> that stores the contents of a file read from a BufferedReader, then convert the contents into a byte[] to allow it to be encrypted using Java's Cipher class.

I have tried using .getBytes() but it's not working since I think I need to convert the ArrayList first, and I'm having trouble on figuring out how to do that.

Code:

// File variable
private static String file;

// From main()
file = args[2];

private static void sendData(SecretKey desedeKey, DataOutputStream dos) throws Exception {
        ArrayList<String> fileString = new ArrayList<String>();
        String line;
        String userFile = file + ".txt";

        BufferedReader in = new BufferedReader(new FileReader(userFile));
        while ((line = in.readLine()) != null) {
            fileString.add(line.getBytes()); //error here
        }

        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, desedeKey);
        byte[] output = cipher.doFinal(fileString.getBytes("UTF-8")); //error here
        dos.writeInt(output.length);
        dos.write(output);
        System.out.println("Encrypted Data: " + Arrays.toString(output));
    }

Many thanks, in advance!

like image 604
munjyong Avatar asked Dec 29 '25 04:12

munjyong


2 Answers

Either concatenate strings, or create a StringBuffer.

StringBuffer buffer = new StringBuffer();
String line;
String userFile = file + ".txt";

BufferedReader in = new BufferedReader(new FileReader(userFile));
while ((line = in.readLine()) != null) {
   buffer.append(line); //error here
}

byte[] bytes = buffer.toString().getBytes();
like image 192
user2914191 Avatar answered Dec 31 '25 17:12

user2914191


Why would you want to read it as string and the convert it to byte array? Since Java 7 you can do:

byte[] input= Files.readAllBytes(new File(userFile.toPath());

then pass that content to the Cipher.

byte[] output = cipher.doFinal(input);

Also you might consider using streams (InputStream and CipherOutputStream) instead of loading the whole file into the memory in case you need handle big files.

like image 32
Veselin Davidov Avatar answered Dec 31 '25 17:12

Veselin Davidov