简体   繁体   English

Android读写应用

[英]Android Read and Write App

I'm trying to create an android application that reads a text file of numbers from the assets folder, then copies those numbers to an array, doubles the value of each number and writes the new set of doubled numbers to the apps external files directory. 我正在尝试创建一个Android应用程序,该应用程序从资产文件夹中读取数字的文本文件,然后将这些数字复制到数组中,将每个数字的值加倍,并将新的双倍数字集写入应用程序外部文件目录。 My app crashes after I input the two file names. 输入两个文件名后,我的应用程序崩溃。 I believe a large part of my error is with the way I tried to write to the external file. 我认为我的大部分错误都与尝试写入外部文件的方式有关。 I have read many different posts and I can't seem to figure out exactly how to write it correctly. 我读过许多不同的文章,但似乎无法弄清楚如何正确编写它。

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

also sorry for asking a nooblike question in advance 也很抱歉提前提出一个nooblike问题

You should try using AssetManager class to open your files from assets: 您应该尝试使用AssetManager类从资产打开文件:

See more here: http://developer.android.com/reference/android/content/res/AssetManager.html 在此处查看更多信息: http : //developer.android.com/reference/android/content/res/AssetManager.html

You can read the file this way: 您可以通过以下方式读取文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM