Java 读取txt文件,并将其显示在不同片段/活动的文本视图中
我正在尝试从Java 读取txt文件,并将其显示在不同片段/活动的文本视图中,java,android,Java,Android,我正在尝试从文件获取文本,并将其应用于文本视图。但是,我将返回文件路径,如下所示 @Override public void onViewCreated(View view, Bundle savedInstanceState){ tv = (TextView) getActivity().findViewById(R.id.clockText); // Displaying the user details on the screen try { get
文件
获取文本,并将其应用于文本视图
。但是,我将返回文件路径
,如下所示
@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
您正在设置file.toString,它返回文件路径。如果要设置文件中存在的数据,则需要在while循环中读取流并附加到stringbuffer,直到文本在文件中结束,最后将stringbuffer.toString设置为textview。按如下操作
@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函数返回一个字符串,然后将该字符串设置为文本视图
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()方法输出的输出,而不是文件内容的输出