我无法访问Android工作室中的txt文件

时间:2017-07-05 07:31:42

标签: android file android-studio

当我尝试在我的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文件相同的包中。 这是我在运行时遇到的错误: 点击此链接查看PICTURE(https://ibb.co/cn3QCv

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

1 个答案:

答案 0 :(得分:0)

不要将您的文本文件放在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);

希望这会奏效。