我在out.txt文件中保存了详细信息,该文件已在data/data/new.android/files/out.txt中创建了一个文本文件.我可以在文本中附加信息,但是,我无法读取此文件.我使用以下过程来读取文件:
File file = new File( activity.getDir("data", Context.MODE_WORLD_READABLE), "new/android/out.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
Run Code Online (Sandbox Code Playgroud)
有人可以帮我解决这个问题吗?
此致,Sunny.
use*_*469 14
@ hermy的答案使用dataIO.readLine(),现已弃用,因此可以在Android中如何阅读文本文件中找到此问题的替代解决方案?.我个人使用@ SandipArmalPatil的答案......完全根据需要做了.
StringBuilder text = new StringBuilder();
try {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"testFile.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close() ;
}catch (IOException e) {
e.printStackTrace();
}
TextView tv = (TextView)findViewById(R.id.amount);
tv.setText(text.toString()); ////Set the text to text view.
Run Code Online (Sandbox Code Playgroud)
her*_*rmy 12
您可以使用以下方式一次读取一行:
FileInputStream fis;
final StringBuffer storedString = new StringBuffer();
try {
fis = openFileInput("out.txt");
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
if ((strLine = dataIO.readLine()) != null) {
storedString.append(strLine);
}
dataIO.close();
fis.close();
}
catch (Exception e) {
}
Run Code Online (Sandbox Code Playgroud)
将if更改为while以全部读取.
小智 8
只需将文件(即命名为yourfile)放在res/raw文件夹中(如果不存在,则可以创建)在项目中.R.raw.yourfile资源将由sdk自动生成.要获取文本文件的String,只需使用以下帖子中Vovodroid建议的代码: Android读取文本原始资源文件
String result;
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.yourfile);
byte[] b = new byte[in_s.available()];
in_s.read(b);
result = new String(b);
} catch (Exception e) {
// e.printStackTrace();
result = "Error: can't show file.";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72643 次 |
| 最近记录: |