我正在尝试从file
获取文本并将其应用于textView
。但是,我将使用file path
返回,如下所示。
@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 :(得分: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()方法输出的输出,而不是文件内容。
答案 1 :(得分:0)
您正在设置file.toString,它返回文件路径。如果你想设置文件中存在的数据,你需要读取流并在while循环中附加到stringbuffer,直到文本在文件中结束,最后将stringbuffer.toString设置为textview。
答案 2 :(得分: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函数返回一个字符串,然后将该字符串设置为文本视图。