【问题标题】:How to properly access a text file in Android Studio如何在 Android Studio 中正确访问文本文件
【发布时间】:2017-07-05 07:31:42
【问题描述】:

当我尝试在我的 Android 应用程序中读取一些文件时,它们似乎不存在,这是我的代码:

public class ReadFiles1 {

    //Static Scanner and File Objects
    static Scanner s;
    

    // Static method that returns an ArrayList
    static ArrayList<String> words (String filename){

        //Instantiate File with file name within parameters
        File n = new File(filename);

        //Instantiate Scanner s with f variable within parameters
        //surround with try and catch to see whether the file was read or not
        try {
            s = new Scanner(n);
        } catch (FileNotFoundException e) {

            e.printStackTrace();
            System.out.println("Problem here");
        }

        //Instantiate a new ArrayList of String type
        ArrayList<String> theWord = new ArrayList <String>();

        //while it has next ..
        while(s.hasNext()){
            //Initialise str with word read
            String str=s.next();

            //add to ArrayList
            theWord.add(str);

        }
        //return ArrayList
        return theWord;

    }

不知道是什么问题,我把txt文件和.java文件放在同一个包里。 这是我在运行时遇到的错误: 检查此链接的图片(https://ibb.co/cn3QCv

W/System.err: java.io.FileNotFoundException: build/numbers.txt: open failed: ENOENT (No such file or directory)

【问题讨论】:

  • 在 Eclipse 中运行良好
  • 请检查Android Mainfest文件是否有权限,如果没有添加权限
  • 检查文件的完整路径,我认为这是唯一的问题..它只是意味着没有这样的文件。
  • @ELITE 我确实写了完整的路径,但是没有用。
  • 显示完整路径并添加您如何调用words 方法..

标签: android file android-studio


【解决方案1】:

不要将文本文件放在 java 文件夹中,而是将其放入

app/src/main/res/raw/ 文件夹并使用以下代码在程序中读取它。

static ArrayList<String> words (InputStream in) {
    try {
        s = new Scanner(in);
    } catch (FileNotFoundException e) {

        e.printStackTrace();
        System.out.println("Problem here");
    }

并使用以下代码从任何活动或服务中调用此方法

InputStream in = getResources().openRawResource(R.raw.numbers);
ArrayList<String> words = ReadFiles1.words(in);

或者如果您从任何其他类调用此方法,那么应该有 context 参考

InputStream in = context.getResources().openRawResource(R.raw.numbers);
ArrayList<String> words = ReadFiles1.words(in);

希望这会奏效。

【讨论】:

  • 我收到此错误消息:W/System.err: java.io.FileNotFoundException: /storage/emulated/0/numbers.txt: open failed: ENOENT (No such file or directory)跨度>
  • 我不明白为什么文件不可见,它们在同一个包中,在 Eclipse 中我没有任何问题...
  • 我只是想说清楚,txt文件在应用程序中,而不是在外部存储中,我只是因为建议.getExternalStorageDirectory()
  • 你把那个txt文件放在哪里..如果你能显示项目结构,那么我可以告诉你原因
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 1970-01-01
  • 2018-10-29
相关资源
最近更新 更多