【问题标题】:Cant create a file in /tmp location of device from API无法从 API 在设备的 /tmp 位置创建文件
【发布时间】:2017-07-24 14:33:48
【问题描述】:

我无法在设备的 /tmp 位置创建文件。我认为这是一些许可问题。你能帮我么..? 在我的 android 清单中,我包含以下权限:-

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

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

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

我的活动代码如下:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method

        try{

            write();

            TextView tv = (TextView) findViewById(R.id.sample_text);
            tv.setText(tv.getText()+"  "+Register());
        //System.out.println("The value of retval is"+nativeinterface());
        }catch (Exception e){e.printStackTrace();}
    }

    public Boolean write(){
        try {

            String fcontent = "Hello world!!";
            String fpath = "/tmp/abc.txt";


            File file = new File(fpath);



            // If file does not exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(fcontent);
            bw.close();

            Log.d("Suceess","Sucess");
            return true;

        } catch (IOException e) {
            System.out.println("The File Not Created");
            e.printStackTrace();
            return false;
        }

    }
}

我的日志如下:

W/System.err: java.io.IOException: Permission denied
W/System.err:     at java.io.UnixFileSystem.createFileExclusively0(Native Method)
W/System.err:     at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
W/System.err:     at java.io.File.createNewFile(File.java:948)

请帮我解决这个问题...

【问题讨论】:

标签: java android


【解决方案1】:

根据documentation,您应该使用Context 对象的getCacheDir() method 来获取保存临时文件的正确位置,即“返回文件系统上应用程序特定缓存目录的绝对路径”。请注意,这适用于 临时 文件,因此如果您想“永久”保存文件(用引号括起来,因为您不能真的假设文件将永久保存在移动设备),您将需要使用不同的方法。再次从文档中,

当设备的其他地方需要磁盘空间时,系统会自动删除该目录中的文件。系统总是会先删除旧文件...

查看this question 以及类似的问题。

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    相关资源
    最近更新 更多