使用时间戳保存文件

时间:2013-03-06 13:59:00

标签: android timestamp

我正在尝试使用时间戳作为名称保存文件。我自己命名时可以保存文件没问题但是当我尝试使用时间戳时它不起作用。这是我的代码:

        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();

        File newxmlfile = new File(Environment.getExternalStorageDirectory()
                 + ts);
        try {
            newxmlfile.createNewFile();
        } catch (IOException e) {
            Log.e("IOException", "exception in createNewFile() method");
        }

        FileOutputStream fileos = null;
        try {
            fileos = new FileOutputStream(newxmlfile);
        } catch (FileNotFoundException e) {
            Log.e("FileNotFoundException", "can't create FileOutputStream");
        }

有谁知道怎么做?

编辑(已解决):我更改了以下行,并使用时间戳作为xml文件保存了文件。

File newxmlfile = new File(Environment.getExternalStorageDirectory()
                 ,ts + ".xml");

1 个答案:

答案 0 :(得分:5)

我认为您使用无效路径创建文件。

当你进行字符串连接时:

Environment.getExternalStorageDirectory() + ts

...您将时间戳123456添加到文件路径(类似)/mnt/sdcard。你最终得到了一条无效的道路,如:

/mnt/sdcard14571747181

(并且你没有写入该文件的权限,因为它不在外部目录中。)

您可以自己添加文件分隔符,也可以使用以下命令创建文件:

File newxmlfile = new File(Environment.getExternalStorageDirectory(), ts);
                                                                    ^^
                                                                the change
相关问题