问题
I am uploading a file "LICENSE.txt" from my PC to Android WebServerApp. NanoHTTPD uses a temporary directory to save the uploaded files. The temporary location is decided by :
tmpdir = System.getProperty("java.io.tmpdir");
and file gets uploaded as : /data/data/com.manmohan.mynanoserver/cache/NanoHTTPD-1736025823 in my case.
After the upload I want to move the file to my SD card "/storage/extSdCard/Uploads".
Here's what I do :
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);
}
I cannot access the /data/. . . directory and files in it, and get error when try to move file.
But this temporary path works :
tmpdir = "/storage/extSdCard/temp-uploads-nanohttpd";
What's wrong with java.io.tmpdir ? If NanoHTTPD can write to it, then why I am not able to move the file ?
回答1:
Since the source and the destination are on different file systems a simple rename is not possible. The documentation for the renameTo
method states:
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.
To solve this, copy the file to the new place and delete it from the old.
来源:https://stackoverflow.com/questions/20869506/move-file-uploaded-from-nanohttpds-temporary-directory-to-sd-card