1

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

代码:

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`
4

3 回答 3

0

使用它来创建文件:

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

正如Java Doc所说:

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. 
于 2012-07-17T07:55:16.983 回答
0

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 参数包含多个空格
在Java中合并路径

于 2012-07-17T08:03:09.507 回答
0
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) {
    ...
}
于 2012-07-17T08:20:22.257 回答