android - 将从 nanohttpd 的临时目录上传的文件移动到 SD 卡

标签 android nanohttpd

我正在将文件“LICENSE.txt”从我的 PC 上传到 Android WebServerApp。 NanoHTTPD 使用一个临时目录来保存上传的文件。临时位置由以下决定:

    tmpdir = System.getProperty("java.io.tmpdir");

文件上传为:/data/data/com.manmohan.mynanoserver/cache/NanoHTTPD-1736025823 在我的例子中。

上传后我想将文件移动到我的 SD 卡“/storage/extSdCard/Uploads”。

这是我的做法:

        String tempFileName = entry.getValue().toString();
        File fileToMove = new File(tempFileName); // temp file path returned by NanoHTTPD

        String p = "/storage/extSdCard/Uploads";
        String newFile = p + "/LICENSE.txt";
        File nf = new File(newFile); // I want to move file here

        if (fileToMove.canWrite()) {
            boolean success = fileToMove.renameTo(nf);
            if (success == true) {
                // LOG to console
                Log.i("FILE_MOVED_TO", newFile);
            } else {
                Log.e("FILE_MOVE_ERROR", tempFileName);
            }
        } else {
            Log.e("PERMISSION_ERROR_TEMP_FILE", tempFileName);
        }

我无法访问 /data/。 . . 目录和其中的文件,尝试移动文件时出错。

但是这个临时路径有效:

    tmpdir = "/storage/extSdCard/temp-uploads-nanohttpd";

java.io.tmpdir 有什么问题?如果 NanoHTTPD 可以写入,那为什么我不能移动文件?

最佳答案

由于源和目标位于不同的文件系统上,因此无法进行简单的重命名。 renameTo 方法的文档指出:

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

要解决此问题,请将文件复制到新位置并将其从旧位置删除。

关于android - 将从 nanohttpd 的临时目录上传的文件移动到 SD 卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20869506/

相关文章:

java - 确保缓存自行获取值的线程安全

java - 为什么即使 "module"和 "sModule"相等,java 代码中的 if 语句也会被跳转

java - 我如何从 Nanohttpd 提供外部 css、jpg 和 gif 文件(Nanohttpd 在普通电脑上运行,而不是在 Android 上运行)?

Android 嵌入式网络服务器

android - 如何使用 NanoHTTPD 在 android 上创建桌面可以访问的 http 服务器(反之亦然)

android - 将 getActivity 作为 LifecycleOwner 传递给 fragment 中 LiveData 的观察方法的原因是什么?

android - 有必要androidtestcompile吗?这是为了什么?

android - 为什么在 NanoHTTPD 上找不到图像和样式文件

android - 带有菜单键的设备上的操作溢出,例如在新的 Google+ 应用程序中

java - NanoHTTPD:显示图像