android - 检查文件是否存在于文件夹中或 Android 中的 sdcard 中

标签 android performance android-download-manager

我正在构建一个 Android 应用程序,它需要一个空数据库位于 sdcard 的特定文件夹中。因此,我构建了一个代码,从服务器下载数据库并以编程方式插入 sdcard,这工作正常。现在的问题是当我从系统运行应用程序时,每次新数据库都通过替换旧数据库来使用。现在我想更改代码,就好像文件夹中不存在数据库文件那么我只需要下载并保存在特定文件夹中

我的代码在这里:

     String DownloadUrl = "http://myexample.com/android/timeexample.db";
     String fileName = "timeexample.db";

     DownloadDatabase(DownloadUrl,fileName);

public void DownloadDatabase(String DownloadUrl, String fileName) {
    try {
        File root = android.os.Environment.getExternalStorageDirectory();
        File dir = new File(root.getAbsolutePath() + "/timeexample/databases");
        if(dir.exists() == false){
             dir.mkdirs();  
        }
        URL url = new URL("http://myexample.com/android/timeexample.db");
        File file = new File(dir,fileName);

        long startTime = System.currentTimeMillis();
        Log.d("DownloadManager" , "download beginning");
        Log.d("DownloadManager" , "download url:" +url);
        Log.d("DownloadManager" , "download file name:" + fileName);

        URLConnection uconn = url.openConnection();
        uconn.setReadTimeout(TIMEOUT_CONNECTION);
        uconn.setConnectTimeout(TIMEOUT_SOCKET);

        InputStream is = uconn.getInputStream();

        BufferedInputStream bufferinstream = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
        int current = 0;
        while((current = bufferinstream.read()) != -1){
            baf.append((byte) current);
        }
        byte[] buffer = new byte[1024];

        FileOutputStream fos = new FileOutputStream( file);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();
        Log.d("DownloadManager" , "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + "sec");

    }

    catch(IOException e) {
        Log.d("DownloadManager" , "Error:" + e);
        e.printStackTrace();
    }   
}

如果每次我这样运行,我的数据都会丢失,因为空数据库正在占用。因此我的要求是如果数据库已经存在,则无需下载。我已经提到了很多例子来解决这个问题。

最佳答案

试试这个:

File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + "/book1/page2.db");

if(myFile.exists()){
...
}

关于android - 检查文件是否存在于文件夹中或 Android 中的 sdcard 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16208659/

相关文章:

android - 在项目上找不到属性 'uninstallDebug'

具有内置热敏打印机的 Android 设备

安卓,Firestore : GlideException: Failed to load resource

mysql - 如何优化此 IP 到位置查找查询?

javascript - 每分钟 JSON 文件解析和合并

android - 下载的文件会自动删除

android - 从内部存储的下载文件夹中打开下载的文件 (pdf)

android - 如果已经在通话并且第二个调用者正在调用,如何不触发 PhoneStateListener.CALL_STATE_RINGING

performance - Excel - VBA - 访问图表轴 - 速度问题

java - 即使应用程序终止,如何在后台使用下载管理器下载多个文件?