在互联网上搜索,找不到合适的代码。 如何获取txt文档的内容并将其返回。
假设我有一个txt文件(src / my.proovi.namespace / data.txt) 我创建了一个名为refresh_all_data()的方法;我想要收集和返回数据。 在主活动方法中,我只需要将内容作为(String content = refresh_all_data();)就可以了。
应该很容易,但却找不到合适的答案。 非常感谢你。
答案 0 :(得分:1)
将该文件放入项目的/assets
文件夹中,然后通过AssetManager
打开InputStream
来获取StringBuilder
:
InputStream in = getAssets().open("data.txt");
然后,您可以使用Reader
从文件中读取行并将其添加到{{3}}:
//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();
答案 1 :(得分:0)
在一个函数中实现以下代码,并在任何地方调用它。
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());
}
答案 2 :(得分:0)
好的,我得到了什么。
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。