2

在我的 android 应用程序中,我遇到了file.exists功能问题。下面是我获取两个变量的函数。from是文件的完整路径,并且to是我必须复制文件的目录路径。例如 from == "/mnt/sdcard/Media/Image/Abstact wallpapers/abstraction-360x640-0033.jpg";to == "/mnt/sdcard";

public static boolean copyFile(String from, String to) {    
            File sd = Environment.getExternalStorageDirectory();
            if (sd.canWrite()) {
                int end = from.toString().lastIndexOf("/") - 1;
                String str1 = from.toString().substring(0, end);
                String str2 = from.toString().substring(end+2, from.length());
                File source = new File(str1, str2);
                File destination= new File(to, str2);
                if (source.exists()) {
                    FileChannel src = new FileInputStream(source).getChannel();
                    FileChannel dst = new FileOutputStream(destination).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    } 

当我调试它时,if (source.exists())返回 false 但我的具有此路径的文件存在。我做错了什么?

4

2 回答 2

4

问题在于您创建File source.

其中存在一个错误,它会生成一个带有错误目录的文件。

因此,当您调用.exists它时根本不会,因为您指的是错误的文件路径

公共字符串子字符串(int start,int end)

自:API 级别 1 返回一个字符串,该字符串包含该字符串的字符子序列。返回的字符串共享此字符串的支持数组。

参数开始第一个字符的偏移量。结束最后一个字符的偏移量。返回一个包含从开始到结束的字符的新字符串 - 1

你误用了substring. 它从头到尾获取子字符串-1。你自己有-1,所以实际上你已经从文件夹目录中把它变成了-2。

如果您删除额外的 -1 并将下一个子字符串的开头减少 1,它应该可以工作。

int end = from.toString().lastIndexOf("/") ;
String str1 = from.toString().substring(0, end);
String str2 = from.toString().substring(end+1, from.length());

编辑:

一种改进的方法是使用这些File方法

File source = new File(from); //creates file from full path name    
String fileName = source.getName(); // get file name
File destination= new File(to, fileName ); // create destination file with name and dir.
于 2012-09-20T16:17:42.857 回答
0

到目前为止看不到任何真正的错误,请确保您在文件系统、fileOutputStream 或 FileChannel#close 上的代码同步可能无法足够快地完成您需要的操作,因为文件系统缓存了一些数据。

看看:http ://docs.oracle.com/javase/1.4.2/docs/api/java/io/FileDescriptor.html

当我主要复制少量数据时,我遇到了这样的问题。

于 2012-09-20T16:21:23.767 回答