【问题标题】:Android: How to check if a file exists on my sdcardAndroid:如何检查我的 SD 卡上是否存在文件
【发布时间】:2015-07-21 12:02:17
【问题描述】:

我正在尝试使用此代码检查我的 sdcard 上是否存在文件,但我遇到了一些问题。我的 Android 手机上的 API 版本是 19,应用程序的 API 版本是 19,但是其他应用程序有很多例外,我不想使用 zedge 等。请给我一些关于如何检查该文件是否存在的提示。

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    File extStore = Environment.getExternalStorageDirectory();
    File myFile = new File(extStore.getAbsolutePath() + "/test.txt");

    if(myFile.exists()){
        Log.d("File", "exists");
    }

}


public boolean isExternalStorage() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

}

我的 Manifest 文件是这样的:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

【问题讨论】:

  • 你会发现很多有相同问题的链接以及他们的解决方案
  • 你的问题太模糊了。您已经在检查文件是否存在。 “其他应用程序的异常”是什么意思?

标签: java android testing


【解决方案1】:

您的代码只是检查文件是否存在于 sdcard/fileName.ext 中:

File extStore = Environment.getExternalStorageDirectory();
    File myFile = new File(extStore.getAbsolutePath() + "/test.txt");

    if(myFile.exists()){
        Log.d("File", "exists");
    }

要搜索整个文件系统(目录树),我们需要一个递归函数,它进入一个目录或将一个文件与搜索文件名进行比较:

public static boolean searchForFile(File root, File mySearchFile)
{
    if(root == null || mySearchFile == null) return; //just for safety   

    if(root.isDirectory())
    {
        Boolean flag = false;
        for(File file : root.listFiles()){
            flag = searchForDatFiles(file, mySearchFile);
            if(flag) return true;
       }
    }
    else if(root.isFile() && root.getName().equals(mySearchFile.getName())
    {
        return true;
    }
 return false;
}

更新

刚刚看到您只在根文件夹中查找文件。检查this 链接以了解检查文件是否存在的四种方法。此外,上面的代码也只适用于 sdcard,但不推荐,因为它会解析它第一次遇到的任何文件夹。适合整个目录树搜索。

【讨论】:

  • 好的,但现在我正在尝试检查此文件是否存在硬编码路径,因为稍后我将尝试对其进行加密。我不需要为具有给定名称的文件搜索整个系统。
猜你喜欢
  • 1970-01-01
  • 2011-02-07
  • 2012-07-02
  • 2011-10-28
  • 2015-06-06
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多