2017-09-23 42 views
1

我試圖將文本數據添加到「fav.txt」文件。我只能添加一個項目到文件並列出。如何將一個或多個項目添加到文件和列表中? 這是我將代碼添加到文件的代碼。openFileOutput獲取數據,但不列出它們

private void writeToFile(String data,Context context) { 
    try { 

     FileOutputStream outputStream; 
     outputStream = openFileOutput("fav.txt", Context.MODE_PRIVATE); 
     outputStream.write(data.getBytes()); 
     outputStream.close(); 
    } 
    catch (IOException e) { 
     Log.e("Exception", "File write failed: " + e.toString()); 
    } 
} 

這個代碼是從文件

public List<String> listele(Context context) throws FileNotFoundException { 
     InputStream inputstream=context.openFileInput("fav.txt"); 
     List<String> listem=new ArrayList<>(); 
    try{ 
     InputStreamReader readeer=new InputStreamReader(inputstream); 
     BufferedReader reader=new BufferedReader(readeer); 
     String line; 
     while((line=reader.readLine())!=null) 
     { 
      listem.add(line); 
     } 
     reader.close(); 
     return listem; 
    } 
    catch (Exception e) 
    { 

     e.printStackTrace(); 
     return null; 
    } 
} 

讀它的工作原理,但只返回一個項目?我怎樣才能解決這個問題?

+0

你想要在你的文件中完全保存什麼? –

+0

@DimaKozhevin只有edittext文本項,當用戶點擊按鈕 – omer1596

+0

你想寫多個字符串嗎?讀取文件中的所有數據? –

回答

0

我檢查了類似的代碼對你的:

public static List<String> listele(String fileName) throws FileNotFoundException { 
    InputStream inputstream = new FileInputStream(fileName); 
    List<String> listem = new ArrayList<>(); 
    try { 
     InputStreamReader readeer = new InputStreamReader(inputstream); 
     BufferedReader reader = new BufferedReader(readeer); 
     String line; 
     while ((line = reader.readLine()) != null) { 
      listem.add(line); 
     } 
     reader.close(); 
     return listem; 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return null; 
    } 
} 

與輸入文件,其中包含example.txt中

line1 
line2 

返回列表中有大小均衡。 2,所以可能你的文件只包含一行。

+0

謝謝你的回答,我做了你做的,但仍然無法正常工作,我收到這條消息「fav.txt:打開失敗:ENOENT(沒有這樣的文件或目錄)「,我沒有.txt仍然是相同的錯誤 – omer1596

+0

檢查文件名是否正確。在我的情況下,它是_src/test/resources/example.txt_。我從測試資源文件夾加載它 –

+0

我正在加載到/data/data/com.project.readerone/files/fav,我檢查測試文件不在這裏我的文件 – omer1596

相關問題