在整个Internet上搜索,找不到有效的代码。我如何获取txt文档的内容并将其返回。
假设我在(src / my.proovi.namespace /data.txt)中有一个txt文件,并且我创建了一个名为refresh_all_data()的方法;我想要收集和返回数据的地方。在主要活动方法中,我只需要将内容作为(String content = refresh_all_data();)就可以了。
应该很容易,但找不到有效的答案。非常感谢你。
将文件放在/assets项目的文件夹中,然后InputStream通过打开文件即可AssetManager:
/assets
InputStream
AssetManager
InputStream in = getAssets().open("data.txt");
然后,您可以从文件中读取行,并将它们添加到StringBuilder使用Reader:
StringBuilder
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();