【问题标题】:How to read from a file in my application on android?如何从我在android上的应用程序中读取文件?
【发布时间】:2015-11-05 14:19:23
【问题描述】:

我在我的电脑上创建了一个文件,我希望我的应用可以从中读取。

如何在我的应用中读取该文件?

谢谢

【问题讨论】:

    标签: android file storage


    【解决方案1】:

    将文件放入assets/(例如,在典型的Android Studio 项目中为app/src/main/assets/)。然后在AssetManager 上使用open() 以在该内容上获得InputStream。您可以通过调用getAssets() 从您的Activity 或其他Context 获取AssetManager

    【讨论】:

    • 谢谢!很有帮助!
    【解决方案2】:

    将文件移动到卡片并添加路径而不是“file.txt”

    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');
            }
    
        br.close();
        }catch (IOException e) {
    //You'll need to add proper error handling here
    }
    
    //Find the view by its id
    TextView tv = (TextView)findViewById(R.id.text_view);
    
    //Set the text
    tv.setText(text);
    

    如果您想阅读文本,这是最好的例子

    【讨论】:

      猜你喜欢
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-03
      • 2017-07-27
      • 1970-01-01
      相关资源
      最近更新 更多