2012-08-28 71 views
0

我知道cours,这里有一些关于这个问题,但我仍然无法找到答案。 我需要在外部存储器中写入一些文本,但是此代码会导致应用程序崩溃。请注意,字符串丹麦人是这个文本。写入文件在外部存储崩溃android应用程序

void zapis2 (String dane){ 
     Context myContext = getApplicationContext(); 
     File file = new File(myContext.getExternalFilesDir(null), "state.txt"); 
     try { 

      FileOutputStream os = new FileOutputStream(file, true); 
      OutputStreamWriter out = new OutputStreamWriter(os); 
       out.write(dane); 
      out.close();}catch (IOException e) { 
       } 
    } 

你有什么想法。我当然在android manifest中添加了permision。

+0

你有书面许可吗? '<使用权限android:name =“android.permission.WRITE_EXTERNAL_STORAGE”/>' – sinisha

+0

请添加堆栈跟踪 – ligi

+0

堆栈跟踪错误在哪里? – user370305

回答

0

试试这个:

File root = android.os.Environment.getExternalStorageDirectory(); 
File dir = new File (root.getAbsolutePath() + "/foldername"); 
dir.mkdirs(); 
File file = new File(dir, "filename.txt"); 

try { 
    FileOutputStream f = new FileOutputStream(file); 
    PrintWriter pw = new PrintWriter(f); 
    pw.println(dane); //your string which you want to store 
    pw.flush(); 
    pw.close(); 
    f.close(); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

希望这有助于!

+0

这是我需要的答案!万分感谢。 – user1433733

0

Contect.getExternalFilesDir(..)只可用于API8,如果您运行/部署在earler版本上它会崩溃。

+0

我使用Android 2.2,所以它正是这个api – user1433733