2016-05-13 14 views
-1

我試圖讓從file文本,並將其應用到textView在TextView中顯示它。但是,如下所示,我將以file path返回。讀txt文件,並在不同的片段/活性

@Override 
public void onViewCreated(View view, Bundle savedInstanceState){ 
    tv = (TextView) getActivity().findViewById(R.id.clockText); 
    // Displaying the user details on the screen 
    try { 
     getFileText(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 


public void getFileText() throws IOException { 
    File path = getActivity().getExternalFilesDir(null); //sd card 
    File file = new File(path, "alarmString.txt"); //saves in Android/ 
    FileInputStream stream = new FileInputStream(file); 
    try{ 
     stream.read(); 
     tv.setText(file.toString()); 
    } finally { 
     stream.close(); 
    } 
} 

結果是"Android/data/foldername/example/files/alarmString.txt",而不是由用戶在例如不同的活動宣佈時間:18:05

回答

0

做如下

@Override 
public void onViewCreated(View view, Bundle savedInstanceState){ 
    tv = (TextView) getActivity().findViewById(R.id.clockText); 
    // Displaying the user details on the screen 
    try { 
     tv.setText(getFileText()); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 


public String getFileText() throws IOException { 
    File path = getActivity().getExternalFilesDir(null); //sd card 
    File file = new File(path, "alarmString.txt"); //saves in Android/ 
    BufferedReader br = new BufferedReader(new FileReader(file)); 
try { 
    StringBuilder sb = new StringBuilder(); 
    String line = br.readLine(); 

    while (line != null) { 
     sb.append(line); 
     sb.append(System.lineSeparator()); 
     line = br.readLine(); 
    } 

} finally { 
    br.close(); 
} 
return sb.toString() 
} 

你不得不返回從getFileText函數的字符串,然後設置該字符串文本視圖。

0

要設置file.toString返回文件的路徑。如果你想設置文件中的數據,你需要讀取流並在while循環中追加到stringbuffer,直到文本在文件中結束,最後將stringbuffer.toString設置爲textview。

1
public String getFileContent(File file) throws IOException { 
    String str = ""; 
    BufferedReader bf = null; 
    try { 
     bf = new BufferedReader(new FileReader(file)); 
     while(bf.ready()) 
      str += bf.readLine(); 
    } catch (FileNotFoundException e){ 
     Log.d("FileNotFound", "Couldn't find the File"); 
    } finally { 
     bf.close(); 
    } 
    return str; 
} 

使用BufferedReader和FileReader代替讀取字節。您使用

stream.read();

什麼給你的文件的一個字節。

tv.setText(file.toString());

將您的TextView設置爲file.toString()方法輸出的輸出而不是文件內容。