簡體   English   中英

轉換ArrayList <String> 到字節[]

[英]Convert ArrayList<String> to byte[]

我希望能夠轉換一個ArrayList<String> ,該ArrayList<String>存儲從BufferedReader讀取的文件的內容,然后將內容轉換為byte []以允許使用Java的Cipher類進行加密。

我嘗試使用.getBytes()但是它不起作用,因為我認為我需要先轉換ArrayList,並且在弄清楚如何做到這一點時遇到了麻煩。

碼:

// 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));
    }

提前謝謝了!

為什么要將其讀取為字符串並將其轉換為字節數組? 從Java 7開始,您可以執行以下操作:

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

然后將該內容傳遞給密碼。

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

另外,如果需要處理大文件,則可以考慮使用流(InputStream和CipherOutputStream),而不是將整個文件加載到內存中。

連接字符串,或創建一個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();

因此,完整的ArrayList實際上是單個String

一種簡單的方法是將其中的所有Strings合並為一個,然后在其上調用.getBytes()

為什么要使用ArrayList。 只需使用StringBuffer並將文件的完整內容保存為單個字符串即可。

將所有字符串合並為Like

String anyName = allstring;

然后叫這個

anyName.getBytes();

它會幫助你。

您可以嘗試利用Java的序列化功能,並使用包裹在ByteOutputStream周圍的ObjectOutputStream:

try (ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout)) {
  out.writeObject(list);
  out.flush();

  byte[] data = bout.toByteArray();
} catch (IOException e) {
  // Do something with the exception
}

這種方法的缺點是字節數組的內容將與列表實現的序列化形式綁定在一起,因此在以后的Java版本中將其讀回List可能會產生奇怪的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM