在互联网上搜索,找不到有效的代码。如何获取 txt 文档的内容并将其返回。
假设我在( src/my.proovi.namespace/data.txt )中有一个 txt 文件,并且我创建了一个名为 refresh_all_data(); 的方法。我希望在哪里收集和返回数据。在主要活动方法中,我只需要将内容获取为( String content = refresh_all_data(); )就是这样。
应该很容易,但只是找不到有效的答案。非常感谢你。
将文件放在/assets
项目的文件夹中,然后您可以InputStream
通过以下方式打开它AssetManager
:
InputStream in = getAssets().open("data.txt");
然后,您可以从文件中读取行并StringBuilder
使用 a将它们添加到Reader
:
//The buffered reader has a method readLine() that reads an entire line from the file, InputStreamReader is a reader that reads from a stream.
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//This is the StringBuilder that we will add the lines to:
StringBuilder sb = new StringBuilder(512);
String line;
//While we can read a line, append it to the StringBuilder:
while((line = reader.readLine()) != null){
sb.append(line);
}
//Close the stream:
reader.close();
//and return the result:
return sb.toString();
在一个函数中实现以下代码并在任何你想要的地方调用它。
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
好的,我得到了什么。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String test = null;
try {
test = refresh_all_data();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView day1Label = new TextView(this);
day1Label.setText(test);
setContentView(day1Label);
}
还有 refresh_all_data(); 方法。
private String refresh_all_data() throws IOException
{
InputStream in = getAssets().open("data.txt");
//The buffered reader has a method readLine() that reads an entire line from the file, InputStreamReader is a reader that reads from a stream.
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//This is the StringBuilder that we will add the lines to:
StringBuilder sb = new StringBuilder(512);
String line;
//While we can read a line, append it to the StringBuilder:
while((line = reader.readLine()) != null){
sb.append(line);
}
//Close the stream:
reader.close();
//and return the result:
return sb.toString();
}
感谢分配给 Jave。