我正在尝试计算一个文本文件中的数字字符,我已经检索到SD卡需要一些建议,这里是android编程新手
使用此代码从SD卡中检索文本文件
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.TextView01);
//Set the text
tv.setText(text);
答案 0 :(得分:1)
假设您已经打开了文件并且没有遇到任何例外,我建议使用它,而不是您正在使用的文件:
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line="";
int c,counter=0;
while ((c = br.read()) != -1) {
line+=(char)c;
counter++;
}
text.append(line);
}
catch (IOException e) {
//You'll need to add proper error handling here
}
在这里,我没有使用text.append("\n")
,因为你的文件已经有换行符了。
在enc counter
中将包含文本计数,包括空格和特殊字符,例如'\ n'