diff options
| author | Daichi Hirono <hirono@google.com> | 2016-03-15 19:19:31 +0900 |
|---|---|---|
| committer | Daichi Hirono <hirono@google.com> | 2016-03-17 13:52:21 +0900 |
| commit | fc7fb7533f46b53247d1e6e6edca6e6c9ac676fe (patch) | |
| tree | 06d72fc6a765384e2c78c4e277413c0ee2d7e4ea /core/java/android/os/FileUtils.java | |
| parent | 62006a72a66ddc5849b28d7ceaaa304b66aa3dc9 (diff) | |
Add suffix number when copying a file.
If we have an existing file in the destination directory, which has the
same name with the source file, adding suffix number is
DocumentsProvider's responsibility.
Because MTP does not provide a way to check existance of files with
given name, the logic is implemented as try-and error strategy. The CL
lets If we MtpDocumentsProvider assume we have a file that shares the
same name with the source file if it failed to invoke
MtpDevice#sendObjectInfo. In this case MtpDocumentsProvider retry to
invoke sendObjectInfo with new name with suffix number.
BUG=26991190
Change-Id: I223ac5031f079bc91eb27709b0356f621a1ed55b
Diffstat (limited to 'core/java/android/os/FileUtils.java')
| -rw-r--r-- | core/java/android/os/FileUtils.java | 37 |
1 files changed, 27 insertions, 10 deletions
diff --git a/core/java/android/os/FileUtils.java b/core/java/android/os/FileUtils.java index 1b79497b1870..dd73e53f65e6 100644 --- a/core/java/android/os/FileUtils.java +++ b/core/java/android/os/FileUtils.java @@ -605,6 +605,30 @@ public class FileUtils { */ public static File buildUniqueFile(File parent, String mimeType, String displayName) throws FileNotFoundException { + final String[] parts = splitFileName(mimeType, displayName); + final String name = parts[0]; + final String ext = parts[1]; + File file = buildFile(parent, name, ext); + + // If conflicting file, try adding counter suffix + int n = 0; + while (file.exists()) { + if (n++ >= 32) { + throw new FileNotFoundException("Failed to create unique file"); + } + file = buildFile(parent, name + " (" + n + ")", ext); + } + + return file; + } + + /** + * Splits file name into base name and extension. + * If the display name doesn't have an extension that matches the requested MIME type, the + * extension is regarded as a part of filename and default extension for that MIME type is + * appended. + */ + public static String[] splitFileName(String mimeType, String displayName) { String name; String ext; @@ -642,18 +666,11 @@ public class FileUtils { } } - File file = buildFile(parent, name, ext); - - // If conflicting file, try adding counter suffix - int n = 0; - while (file.exists()) { - if (n++ >= 32) { - throw new FileNotFoundException("Failed to create unique file"); - } - file = buildFile(parent, name + " (" + n + ")", ext); + if (ext == null) { + ext = ""; } - return file; + return new String[] { name, ext }; } private static File buildFile(File parent, String name, String ext) { |
