2011-05-20 25 views
0

谁能告诉我为什么我的下面的代码不起作用?我试图追加一个字符串到文本/ html文件的内容。我只是跟着在Android开发文档代码hereAndroid:写入文件不能正常工作

package com.example.GetContentThenAppend; 

import java.io.FileOutputStream; 
import java.io.IOException; 

import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.os.Environment; 

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

     try { 
      String FILENAME = Environment.getExternalStorageDirectory() + "/EngagiaDroid/videos.html"; 
      String string = "<div style='color: blue; border: thin solid red;'>YO!</div>"; 

      FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND); 
      fos.write(string.getBytes()); 
      fos.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 
} 
+0

错误是什么?你怎么知道它不工作? – Haphazard 2011-05-20 17:14:35

+0

感谢您的回复,当我运行此代码时,我收到强制关闭消息... – Kris 2011-05-20 17:18:13

+2

请查看logcat以获取错误消息。 http://developer.android.com/guide/developing/tools/logcat.html – Haphazard 2011-05-20 17:18:59

回答

2

我猜你的问题的权限,,有你在你的清单中添加写入文件的权限。您可以通过将此添加到清单文件来执行此操作

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
0

确保您有correct permissions写入文件。在你manifest file,包括该行

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
0

确保您已创建目录EngagiaDroid。我建议你 打电话

new File(Environment.getExternalStorageDirectory() + "/EngagiaDroid").mkdirs(); 

保存文件之前。