简体   繁体   中英

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. 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

You should try using AssetManager class to open your files from assets:

See more here: 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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