我想检查我的包文件夹中是否存在文件,但我不想创建新文件。
File file = new File(filePath);
if(file.exists())
return true;
此代码是否会在不创建新文件的情况下进行检查?
您的代码块不会创建新的代码块,它仅检查它是否已经存在而没有其他内容。
File file = new File(filePath);
if(file.exists())
//Do something
else
// Do something else.
当您使用此代码时,您并不是创建一个新文件,它只是为该文件创建一个对象引用并测试它是否存在。
File file = new File(filePath);
if(file.exists())
//do something
它对我有用:
File file = new File(getApplicationContext().getFilesDir(),"whatever.txt");
if(file.exists()){
//Do something
}
else{
//Do something else
}
当您说“在您的包文件夹中”时,您是指您的本地应用程序文件吗?如果是这样,您可以使用 Context.fileList() 方法获取它们的列表。只需迭代并查找您的文件即可。假设您使用 Context.openFileOutput() 保存了原始文件。
示例代码(在活动中):
public void onCreate(...) {
super.onCreate(...);
String[] files = fileList();
for (String file : files) {
if (file.equals(myFileName)) {
//file exits
}
}
}
Path 类中的
methods
是语法性的,意味着它们对 Path 实例进行操作。但最终您必须访问 file
系统来验证特定路径是否存在
File file = new File("FileName");
if(file.exists()){
System.out.println("file is already there");
}else{
System.out.println("Not find file ");
}
if(new File("/sdcard/your_filename.txt").exists())){
// Your code goes here...
}
public boolean FileExists(String fname) {
File file = getBaseContext().getFileStreamPath(fname);
return file.exists();
}
创建 File 对象时不会创建任何文件,它只是一个接口。
为了更轻松地处理文件,Uri 上有一个现有的
.toFile
函数
您还可以在 File 和/或 Uri 上添加扩展属性,以进一步简化使用。
val File?.exists get() = this?.exists() ?: false
val Uri?.exists get() = File(this.toString).exists()
然后只需使用
uri.exists
或 file.exists
进行检查。