【问题标题】:File does not created in android?文件不在android中创建?
【发布时间】:2012-07-16 02:50:24
【问题描述】:

当我尝试创建新文件时,收到一条错误消息。

代码:

try 
{
    File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
    Runtime.getRuntime().exec("chmod 777 " + root.getAbsolutePath());
    File myFile = new File(root,"createNew.txt");
    myFile.createNewFile();
}
catch(Exception e)
{
    Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}

错误信息:

java.io.IOException: open failed: EACCES (Permission denied)

/mnt/sdcard 权限为d---------

如何通过编程更改权限?如何解决。给我任何想法。

提前致谢。

注意这一点:

当我在命令提示符中使用此代码时,文件已成功创建,该代码为:

`chmod 777 /mnt/sdcard`

【问题讨论】:

  • 你给Write_External_storage权限了吗?在您的 Manifest.xml 中授予此权限
  • 我已经添加了这个权限。
  • 你是在你的设备或模拟器中尝试这个吗?
  • 确保。两者都有 SD 卡存储?
  • File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath()); 我已经尝试过这个,现在我尝试访问模拟器。

标签: android file permissions


【解决方案1】:
try {
    File filename = new File(Environment.getExternalStorageDirectory() +
                             "/yourfilename.txt");
    filename.createNewFile();
    FileWriter writer = new FileWriter(filename2); 
    writer.write("Your content");
    writer.flush(); 
    writer.close();
} catch (IOException e) {
    ...
}

【讨论】:

  • 请不要宣传e.printStackTrace()。这是个坏习惯。那些默认设置的 IDE 真的很讨厌你。
【解决方案2】:

1-用这个来获取你的sdk目录:

Environment.getExternalStorageDirectory().getAbsolutePath();      

2-或者可能是你的文件路径有一些非法字符(如空格),在这种情况下你需要用合法的等号替换它们。例如空格用“\”。你可以看到这个页面:Runtime.getRuntime().exec()
http://www.coderanch.com/t/498450/java/java/exec-command-not-able-deal
Runtime.exec on argument containing multiple spaces
Combine paths in Java

【讨论】:

  • 现在看我的问题。当我试图以编程方式设置权限时,当时我无法创建新文件。当我试图通过command prompt 设置权限时,它正在工作。
  • 我只需要访问创建一个新文件。什么都不写。只需创建一个文件。
【解决方案3】:

使用它来创建文件:

FileOutputStream fos= new FileOutputStream(outputPath);
//fos.write(...);
fos.close();

正如 Java 文档所说:

This method is not generally useful. For creating temporary files, use  
`createTempFile(String, String)` instead. For reading/writing files, use 
FileInputStream, FileOutputStream, or RandomAccessFile, all of which can create 
files. 

【讨论】:

猜你喜欢
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多