2013-10-02 101 views
1

我試圖創建一個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(); 
    } 
} 

也對不起,問一個nooblike問題提前

+1

你可以共享日誌當你的應用程序崩潰時在控制檯中顯示?看起來這條線有問題:'File inFile = new File(「file:/// android_asset /」+ fileLoc);' – Peshal

+0

另外,你不要在你的問題中提及它,但要確保你有[WRITE_EXTERNAL_STORAGE ](http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE)清單中的權限。 – Karl

回答

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(); 
相關問題