2011-09-15 61 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

相关问题