如何在安卓设备上读取文本文件?

13

我正在将细节保存在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));

有谁能帮我解决这个问题吗?

谢谢, Sunny。


什么意思是“无法读取此文件”? - RoflcoptrException
我的意思是,我正在尝试从文件out.txt中读取内容。 - sunny
3个回答

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.

13

你可以使用以下方法逐行读取:

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以便全部读取。


1
openFileInput不起作用。 - Shirish Herwade
1
同时,readline已经被弃用,请不要使用以上内容。 - Shirish Herwade

9
只需将文件(例如命名为yourfile)放入项目内的res/raw文件夹中(如果不存在,可以创建)。SDK会自动生成R.raw.yourfile资源。 要获取文本文件的字符串,请使用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.";
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接