Android读写应用程序

时间:2013-10-02 03:03:33

标签: java android

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

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();
    }
}

也很抱歉提前提出了一个禁忌的问题

1 个答案:

答案 0 :(得分: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();