我有我的安卓活动:
try {
File root=Environment.getExternalStorageDirectory();
Log.i("root",root.toString());
File dir=new File(root.getAbsolutePath() + "/downloads");
dir.mkdirs();
file=new File(dir,"mytext.txt");
FileOutputStream out=new FileOutputStream(file,true);
PrintWriter pw=new PrintWriter(out);
pw.println("Hello! Welcome");
pw.println("You are Here...!!!");
pw.flush();
pw.close();
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
还补充道:
<uses-permission android:name="androd.permission.WRITE_EXTERNAL_STORAGE"/>
但它抛出了FileNotfound异常: 01-13 09:06:44.442:WARN / System.err(419):java.io.FileNotFoundException:/mnt/sdcard/downloads/mytext.txt(没有这样的文件或目录)
如果我添加
if(file.exists()){
System.out.println("file exists");
}
else{
System.out.println("No such Fileeeeeeeeee");
}
它进入“其他”部分。
感谢
斯纳
答案 0 :(得分:8)
试试这个,它对我有用
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
//now attach OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
答案 1 :(得分:7)
在Android 6(Marshmallow)中,我必须明确检查我的应用是否有权限"WRITE_EXTERNAL_STORAGE"
答案 2 :(得分:0)
不确定,但请确认您的模拟器或手机中存在外部存储,否则将通过例外。