2011-09-15 74 views
0

我正在嘗試使用java FileInputStream將一些字符串寫入將存儲在android內部存儲上的文本文件。然而,我的虛擬設備不斷拋出一個異常,我不知道我應該看什麼或在哪裏,因爲DDMS日誌貓功能不給我任何有用的信息。我正在使用帶有堆棧跟蹤打印的try/catch結構,如下所示。我對android的調試功能不是很熟悉,我不知道我還能在哪裏找到發生的事情。代碼如下。如何在Android中使用eclipse調試

import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

public class MainActivity extends Activity { 
    private EditText textBox; 
    private static final int READ_BLOCK_SIZE = 100; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     textBox = (EditText)findViewById(R.id.textView1);   

     Button saveBtn = (Button)findViewById(R.id.button1); 
     Button loadBtn = (Button)findViewById(R.id.button2); 

     saveBtn.setOnClickListener(new View.OnClickListener() {   
      public void onClick(View v) { 
       String str = textBox.getText().toString(); 
       try{ 
        FileOutputStream fOut = 
         openFileOutput("textfile.txt", MODE_WORLD_READABLE); 
        OutputStreamWriter osw = new OutputStreamWriter(fOut); 

        //---write the string to the file--- 
        osw.write(str); 
        osw.flush(); 
        osw.close(); 

        //---display file saved message--- 
        Toast.makeText(getBaseContext(), "File saved successfully!!", Toast.LENGTH_SHORT).show(); 

        //---clears the EditText--- 
        textBox.setText(""); 

       }catch(IOException ioe){ 
        ioe.printStackTrace(); 
       } 
      } 
     }); 

     loadBtn.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       try{ 
        FileInputStream fIn = openFileInput("textfile.txt"); 
        InputStreamReader isr = new InputStreamReader(fIn); 

        char[]inputBuffer = new char[READ_BLOCK_SIZE]; 
        String s = ""; 

        int charRead; 
        while((charRead = isr.read(inputBuffer))>0){ 

         //---convert the char to a String--- 
         String readString = String.copyValueOf(inputBuffer, 0, charRead); 
         s += readString; 

         inputBuffer = new char[READ_BLOCK_SIZE]; 
        } 
        //---set the EditText to the text that has been read--- 
        textBox.setText(s); 

        Toast.makeText(getBaseContext(), "File loaded successfully!!", Toast.LENGTH_SHORT).show(); 
       }catch(IOException ioe){ 
        ioe.printStackTrace(); 
       } 
      } 
     }); 
    } 
} 

回答

0

您是否在您的清單中爲您的書寫設置了權限? 並且是您的設備droidx(當您插入USB電纜時,卸載外部存儲,使其無法訪問)。

爲什麼不運行調試器並放入調試點並查看它在崩潰之前得到了多少?

+0

我寫信給內部存儲器,所以我不必擔心外部卸載。那將是我下一個項目。我沒有增加寫作權限,因爲我認爲只有寫入外部的權限,而不是內部的權限。 – JCC

相關問題