如何在Android中读取文本文件?
我正在out.txt文件中保存详细信息,该文件在data/data/new.android/files/out.txt中创建了一个文本文件。 我能够将信息附加到文本中,但是,我无法读取此文件。我使用以下步骤读取该文件:如何在Android中读取文本文件?,android,Android,我正在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(
File file = new File( activity.getDir("data", Context.MODE_WORLD_READABLE), "new/android/out.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
有人能帮我解决这个问题吗
问候,,
Sunny。您可以使用以下命令一次读一行:
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) {
}
将if改为while以阅读所有内容。@hermy的答案使用了
dataIO.readLine()
,该选项现已弃用,因此可以在中找到此问题的替代解决方案。我个人使用了@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.
只需将您的文件(即命名为yourfile)放入项目中的res/raw文件夹(如果不存在,您可以创建)。sdk将自动生成R.raw.yourfile资源。
要获取文本文件的字符串,只需使用Vovodroid在以下帖子中建议的代码:
什么意思是“无法读取此文件”?我的意思是,我正在尝试从文件中读取内容。txtopenFileInput不起作用。readline已弃用,因此不要使用上面的命令
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.";
}