2017-02-24 61 views
1

我有2個java類。讓他們成爲A級B級將FIile內容讀爲字節java

A類從用戶得到字符串輸入並存儲作爲字節到該文件,則B類應該讀取文件,並顯示作爲字節串的輸入端。

CLASS A:

File file = new File("C:\\FILE.txt"); 

file.createNewFile(); 

FileOutputStream fos = new FileOutputStream(file); 
String fwrite = user_input_1+"\n"+user_input_2; 
fos.write(fwrite.getBytes()); 
fos.flush(); 
fos.close(); 

在B類,我寫的代碼讀取該文件,但我不知道如何讀取文件內容字節。

B類:

fr = new FileReader(file); 
br = new BufferedReader(fr); 
arr = new ArrayList<String>(); 
int i = 0; 

while((getF = br.readLine()) != null){ 
    arr.add(getF); 
} 
String[] sarr = (String[]) arr.toArray(new String[0]); 

的FILE.TXT具有以下線

[B @ 3ce76a1

[B @ 36245605

我希望兩個這些線轉換分成各自的字符串值,然後顯示它們。怎麼做?

回答

1

既然你正在編寫通過FileOutputStream中的字節數組,相反的操作將讀取使用FileInputStream中的文件,從字節數組構造字符串:

File file = new File("C:\\FILE.txt"); 
Long fileLength = file.length(); 
byte[] bytes = new byte[fileLength.intValue()] 
try (FileInputStream fis = new FileInputStream(file)) { 
    fis.read(bytes); 
} 
String result = new String(bytes); 

不過,也有更好的方法將字符串寫入文件。

您可以使用FileWriter編寫它,並使用FileReader讀取(可能用相應的BufferedReader/Writer包裝它們),這將避免創建中間字節數組。或者更好的是,使用Apache Commons的IOUtils或谷歌的Guava庫。