【问题标题】:Create a .nonmedia File in Android doesnt work在 Android 中创建 .nomedia 文件不起作用
【发布时间】:2012-07-19 18:52:44
【问题描述】:

我的应用程序创建并使用 sd 卡中的一些图像。 这些图像显示在设备的图库中,但我不希望这样。 所以我试图在这个目录中创建一个 .nonmedia 文件,但我的问题是这个文件不会被创建。

代码如下:

public void createNonmediaFile(){
    String text = "NONEMEDIA";
    String path = Environment.getExternalStorageDirectory().getPath() + "/" +  AVATARS + "/.nonmedia";
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(path);
        fos.write(text.getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

没有例外。

我猜它与“。”有关。在名字里。如果我尝试同样的方法,文件就会被创建。

感谢您的帮助。

【问题讨论】:

  • 该文件应称为.nomedia。请注意与您所拥有的拼写差异。

标签: android file sd-card


【解决方案1】:

试试下面的例子

    File file = new File(directoryPath, ".nomedia");
    if (!file.exists()) {
        try {
            file.createNewFile();
        }
        catch(IOException e) {

        }
    }

【讨论】:

    【解决方案2】:

    在您的 android-manifest 文件中添加以下权限:

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

    然后下面的代码应该可以正常工作:

    private static final String AVATARS = "avatars";
    public void createNonmediaFile(){
        String text = "NONEMEDIA";
        String path = Environment.getExternalStorageDirectory().getPath() + "/" +  AVATARS + "/.nonmedia";
        String f = Environment.getExternalStorageDirectory().getPath() + "/" +  AVATARS ;
        FileOutputStream fos;
        try {
            File folder = new File(f);
            boolean success=false;
            if (!folder.exists()) {
                success = folder.mkdir();
            }
            if (true==success) {
                File yourFile = new File(path);
                if(!yourFile.exists()) {
                    yourFile.createNewFile();
                } 
            } else {
            // Do something else on failure 
            }
            fos = new FileOutputStream(path);
            fos.write(text.getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      相关资源
      最近更新 更多