2015-05-28 82 views
-7

我對如何加密和解密字符串有基本的瞭解。我有我自己開發的密碼,但它只適用於字符串,所以我想把它帶到下一個級別。文件到字符串或字符串到文件

如何將File轉換爲String,並將String轉換回File,以便我可以使用自己的密碼來加密文件?

+6

這是說,滑稽的方式, 「我有功課」 – Adam

+0

手冊應用密碼學的:HTTP:// cacr.uwaterloo.ca/hac/ – aGer

+3

這並不能真正回答你的問題,但爲什麼開發自己的加密?已經有很多東西可以保證比你提出的更安全。如果他們不是,你應該寫一篇論文,並在CS歷史上佔據你應有的位置。 – yshavit

回答

1

請注意,有很多方法來讀取和寫入文件,這可能不是最佳的解決方案。

寫在文件中的字符串:

public void writeInFile(String string, File file) 
{ 
    try 
    { 
    byte[] content = string.getBytes(); 
    FileOutputStream out = new FileOutputStream(file); 
    out.write(content); 
    out.flush(); 
    out.close(); 
    } 
    catch (IOException e) 
    { 
    throw new RuntimeException(e); 
    } 

} 

從文件中讀取:

public String readFromFile(File file) 
{ 
    try 
    { 
     FileInputStream fileInputStream = new FileInputStream(file); 
     byte[] fileContent = new byte[(int) file.length()]; 

     fileInputStream.read(fileContent); 
     fileInputStream.close(); 

     return new String(fileContent); 
    } 
    catch (IOException e) 
    { 
     throw new RuntimeException(e); 
    } 
} 
+0

謝謝,字節數組就是我尋找! –