0

我想读取一个文本文件,将其转换为字节数组,处理字节数组,然后将其写入另一个文件。为此,我不想丢失任何换行符,因此新行也应写入上一步创建的新文件中。这是我到目前为止所做的:

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

将 filePath和fileName作为上述代码片段中的有效标识符。

4

2 回答 2

2

我不明白您为什么要将使用 StringBuilder 组成的字符串转换为字节数组,但是,请尝试以下代码:

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"));

输出:

Before conversion:
hallo!
How do
you do?

After conversion:
hallo!
How do
you do?
于 2014-03-28T08:49:24.753 回答
0

将加密行直接写为字节并使用 CRLF 作为分隔符是没有意义的,因为 CRLF 是加密数据的合法字节序列。

您还需要以兼容的格式对每个加密行进行编码,例如 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);
    }

}

更新

仅根据您的要求,这是您应该期望的:

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);
于 2014-03-28T08:49:17.553 回答