【问题标题】:getting file not found exception获取文件未找到异常
【发布时间】:2012-01-13 03:28:17
【问题描述】:

我有我的安卓活动:

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");  
   }  

它进入“其他”部分。

谢谢
斯内哈

【问题讨论】:

  • 您必须使用 getExternalStorageState() 方法检查媒体是否可用。
  • 可用,可读可写。
  • 你能解释一下你在用“dir.mkdirs()”做什么吗?
  • 创建一个包含sdcard完整路径的新目录

标签: android filenotfoundexception


【解决方案1】:

试试这个,它对我有用

// 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);

GO through this for more details

【讨论】:

    【解决方案2】:

    在 Android 6 (Marshmallow) 中,我必须明确检查我的应用是否有权限 "WRITE_EXTERNAL_STORAGE"

    【讨论】:

    【解决方案3】:

    不确定,但请确认您的模拟器或手机中存在外部存储,否则会出现异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 2019-06-26
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多