gpt4 book ai didi

java - android file.exists 不能正常工作

转载 作者:搜寻专家 更新时间:2023-11-01 08:08:07 26 4
gpt4 key购买 nike

在我的 android 应用程序中,我遇到了 file.exists 函数的问题。下面是我的函数,它获取两个变量。 from 是文件的完整路径,to 是我必须复制文件的目录路径。例如来自 == "/mnt/sdcard/Media/Image/Abstact wallpapers/abstraction-360x640-0033.jpg";== "/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 但我的文件存在此路径。我做错了什么?

最佳答案

问题在于您创建 File source 的方式。

其中存在一个错误,即生成目录错误的文件。

所以当你调用 .exists 时它根本不存在,因为你指的是错误的文件路径

public String substring (int start, int end)

Since: API Level 1 Returns a string containing a subsequence of characters from this string. The returned string shares this string's backing array.

Parameters start the offset of the first character. end the offset one past the last character. Returns a new string containing the characters from start to end - 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.

关于java - android file.exists 不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12516371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com