1

我正在尝试创建一个 android 应用程序,它从 assets 文件夹中读取数字文本文件,然后将这些数字复制到一个数组中,将每个数字的值加倍并将新的加倍数字集写入应用程序外部文件目录。输入两个文件名后,我的应用程序崩溃。我相信我的错误很大一部分与我尝试写入外部文件的方式有关。我已经阅读了许多不同的帖子,但我似乎无法确切地弄清楚如何正确编写它。

public void readArray() {

    EditText editText1;
    EditText editText2;
    TextView tv;

    tv = (TextView) findViewById(R.id.text_answer);
    editText1 = (EditText) findViewById(R.id.input_file);
    editText2 = (EditText) findViewById(R.id.output_file);

    int numGrades = 0;
    int[] gradeList = new int[20];

    String fileLoc = (String) (editText1.getText().toString());

    try {
        File inFile = new File("file:///android_asset/" + fileLoc);
        Scanner fsc = new Scanner(inFile);

        while (fsc.hasNext()) {
            gradeList[numGrades] = fsc.nextInt();
            numGrades++;
        }
    } catch (FileNotFoundException e) {
        tv.append("error: file not found");
    }

    for (int i = 0; i < gradeList.length; i++) {
        gradeList[i] = gradeList[i] * 2;
    }

    String fileLoc2 = (String) (editText2.getText().toString());

    FileWriter fw;

    //new code
    File root = Environment.getExternalStorageDirectory();
    File file = new File(root, fileLoc2);

    try {
        if (root.canWrite()) {
            fw = new FileWriter(file);

            //PrintWriter pw = new PrintWriter(fw);
            BufferedWriter out = new BufferedWriter(fw);

            for (int i = 0; i < gradeList.length; i++) {
                out.write(gradeList[i]);
            }
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

也很抱歉提前问了一个类似菜鸟的问题

4

1 回答 1

0

您应该尝试使用AssetManager类从资产中打开文件:

在这里查看更多信息:http: //developer.android.com/reference/android/content/res/AssetManager.html

您可以这样读取文件:

AssetManager am = context.getAssets();     
InputStream is = am.open("text");       
BufferedReader in = new BufferedReader(new InputStreamReader(is));       
String inputLine;       
while ((inputLine = in.readLine()) != null)         
    System.out.println(inputLine);
in.close();
于 2013-10-02T03:36:06.517 回答