找不到文本文件

时间:2017-03-12 19:50:03

标签: android readfile

我基本上试图从文本文件中读取一长串数字(双打)并将它们保存到数组中。我有这些代码行,但当我加载到我的Android智能手机时,它不起作用。当我使用调试模式检查我的代码是否读取ExamScore时,readfile()确实可以正常工作,它确实读取并存储我的笔记本电脑中预期的值。当它加载到智能手机时,它只是不起作用。我将ExamScore.txt保存在android studio的根目录中,例如,Users-> AndroidStudioProjects-> Project A.我主要担心的是:

  1. 如何在构建应用时将此ExamScore.txt保存到我的智能手机中?我是否必须单独将文本文件保存到我的智能手机中?我得到的错误是
  2. java.io.FileNotFoundException:ExamScore.txt:open failed:ENOENT(没有这样的文件或目录)

    static double[] readfile() throws FileNotFoundException{
    
        Scanner scorefile = new Scanner(new File("ExamScore.txt"));
        int count = -1;
        double[] score = new double[8641];
        while (scorefile.hasNext()) {
            count = count + 1;
            score[count] = Double.parseDouble(scorefile.nextLine());
        }
        scorefile.close();
        return score;
    }
    

    在我的主要代码中,

    double []score=readfile();
    

2 个答案:

答案 0 :(得分:2)

  

我将ExamScore.txt保存在android studio的根目录中,例如,Users-> AndroidStudioProjects-> Project A ...我怎么知道这个ExamScore.txt是否也保存到我的智能手机中我构建应用程序?

不是。

您需要创建资产文件夹。

参考:Where do I place the 'assets' folder in Android Studio?

您可以使用getAssets()从该文件夹中读取。

public class MainActivity extends Activity {

    private double[] readfile() throws FileNotFoundException{

        InputStream fileStream = getAssets().open("ExamScore.txt");
        // TODO: read an InputStream

    }
}

注意:这是您应用的只读位置。

或者您可以使用内部SD卡。

How do I read the file content from the Internal storage - Android App

编辑使用其他答案中的重构代码

public static List<Double> readScore(Context context, String filename)  {

    List<Double> scores = new ArrayList<>();

    AssetManager mgr = context.getAssets();
    try ( 
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(mgr.open(fileName)));
    ) {
        String mLine;
        while ((mLine = reader.readLine()) != null) {
             scores.add(Double.parseDouble(mLine));
        }
    } catch (NumberFormatException e) {
        Log.e("ERROR: readScore", e.getMessage());
    }
    return scores;
}

然后

List<Double> scores = readScore(MainActivity.this, "score.txt");

答案 1 :(得分:0)

对于那些想知道的人,这是我的解决方案!感谢大家的帮助!!!!我遇到的问题是我没有在主活动中写它,而是在其他java文件中编写代码。在主活动文件中写入此文件并将我的文本文件放在assets文件夹中之后。问题已解决:

public static LinkedList<Double> score=new LinkedList<Double>();
public  void readScore() throws java.io.IOException {
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(getAssets().open("score.txt")));
    String mLine;
    while ((mLine = reader.readLine()) != null) {
         score.add(Double.parseDouble(mLine));
    }
    reader.close();
}