2014-03-28 26 views
0

我想讀取文本文件,將其轉換爲字節數組,然後將其寫入另一個文件。爲此,我不想丟失任何換行符,以便新行也應寫入上一步創建的新文件中。這是我迄今所做的:如何在將字節數組轉換爲字符串後將新的行字符寫入Java文件

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

採取文件路徑文件名作爲有效的標識符在上面的代碼片斷。

+0

你也可以嘗試' 「%N」' –

+0

你想在文件中的每一行seperatly,加密除了換行符? – Chriss

回答

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

} 

UPDATE

僅根據你的要求,這是你應該期待什麼:

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); 
+0

我正在Java和CBC中實施CBC,你需要有完整的明文信息,然後將它們送到合適的庫函數進行加密處理。 @michele – DecodingLife

+0

-1,這不是你的問題所指出的。糾正你的問題,我會刪除downvote,並嘗試回答如果我可以。 –

+0

我的問題只是關於文件處理,沒有什麼比這更多或更少。我不是在談論加密或任何事情。 - @ michele – DecodingLife

2

我不明白你爲什麼要將使用StringBuilder組成的字符串轉換爲字節數組,但是n evertheless,試試這個代碼:

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? 
+0

我想寫入一個文件,而不是隻是打印在控制檯上。在你的情況下,我想'行'被寫入一個文本文件(比方說),所有新的行在他們的適當位置。 @harmlezz – DecodingLife

+0

我的代碼是一個例子,如何做到這一點。我使用控制檯,但是你可能對你的文件完全一樣。只需使用正確的編碼方式就像我在每一步中所做的那樣現在不應該爲你而努力吧? – Harmlezz

+0

是的,希望如此。但是我只是在寫入文件時遇到問題。如果我仍然面臨使用ByteArrayOutputStream寫入文件的相同問題,會出現問題。 - @harmlezz – DecodingLife

相關問題