Android 下载重复文件命名规则【android源码解析七】

      去年4月份的时候,我有一个任务,让我写个下载保存文件的方法,如果文件的名字存在,就加“-1”,如果仍然存在,就在-后面的数字加1,例如:文件名:Keep_On_It.mp3,第一次下载是Keep_On_It.mp3,第二次下载名字就保存成:Keep_On_It-1.mp3,第三次下载名字就保存成:Keep_On_It-2.mp3,第四次下载名字就保存为:Keep_On_It-3.mp3,以此类推的形式一直实现。当时我用的方法比较笨,可读性特别差,当时用了半天就实现了,就是截取字符串进行比较。最近研究源码下载的时候发现可以用for循环来实现,可读性强,容易理解,算法简练,不愧为谷歌设计出来的,简单明了,容易理解。

转载请标明出处http://blog.csdn.net/wdaming1986/article/details/7342559

       现在给大家分享一下:先看效果图片:

               如果内存卡的这个目录只有这些MP3:

                                                        

                   再次保存的名字就是最后一个Keep_It_On-3.mp3了

                                                      

 

        下面把代码奉上:

在CopyFileApp的工程里:

一、在com.cn.daming.copyfile包下的CopyFileAppActivity.java类中的代码:

[java]  view plain copy print ?
  1. package com.cn.daming.copyfile;  
  2.   
  3. import java.io.File;  
  4. import java.util.Random;  
  5.   
  6. import android.app.Activity;  
  7. import android.app.AlertDialog;  
  8. import android.os.Bundle;  
  9. import android.os.Environment;  
  10. import android.os.SystemClock;  
  11. import android.util.Log;  
  12. import android.widget.TextView;  
  13.   
  14. public class CopyFileAppActivity extends Activity {  
  15.     /** Called when the activity is first created. */  
  16.       
  17.     private final static String SDCARD_PATH="/mnt/sdcard/download/mp3/Keep_It_On.mp3";  
  18.     private final static String FILENAME_SEQUENCE_SEPARATOR = "-";  
  19.     private static Random sRandom = new Random(SystemClock.uptimeMillis());  
  20.     private final static String LOG = "wangxianming";  
  21.       
  22.     private TextView m_TextView;  
  23.     private TextView m_TextView_full;  
  24.       
  25.     @Override  
  26.     public void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.main);  
  29.           
  30.         m_TextView = (TextView)findViewById(R.id.text_view);  
  31.         m_TextView_full = (TextView)findViewById(R.id.text_view2);  
  32.           
  33.         Log.v(LOG, " ---->"+SystemClock.uptimeMillis());  
  34.           
  35.         // Check to see if we have an SDCard  
  36.         String status = Environment.getExternalStorageState();  
  37.         if (!status.equals(Environment.MEDIA_MOUNTED)) {  
  38.             int title;  
  39.             String msg;  
  40.             // Check to see if the SDCard is busy, same as the music app  
  41.             if (status.equals(Environment.MEDIA_SHARED)) {  
  42.                 msg = getString(R.string.download_sdcard_busy_dlg_msg);  
  43.                 title = R.string.download_sdcard_busy_dlg_title;  
  44.             } else {  
  45.                 msg = getString(R.string.download_no_sdcard_dlg_msg, "no sdcard");  
  46.                 title = R.string.download_no_sdcard_dlg_title;  
  47.             }  
  48.   
  49.             new AlertDialog.Builder(this)  
  50.                 .setTitle(title)  
  51.                 .setIcon(android.R.drawable.ic_dialog_alert)  
  52.                 .setMessage(msg)  
  53.                 .setPositiveButton(R.string.ok, null)  
  54.                 .show();  
  55.             return;  
  56.         }  
  57.           
  58.         File mp3File = new File(SDCARD_PATH);  
  59.         if(mp3File != null && mp3File.exists()) {  
  60.             String fileNamePath = mp3File.getAbsolutePath();  
  61.             String filename = fileNamePath.substring(0, fileNamePath.lastIndexOf("."));  
  62.             String extension = fileNamePath.substring(fileNamePath.lastIndexOf("."), fileNamePath.length());  
  63.             m_TextView.setText(filename + extension);  
  64.             m_TextView_full.setText(chooseUniqueFilename(filename, extension));  
  65.         }  
  66.     }  
  67.       
  68.     //This is method is core  
  69.     private String chooseUniqueFilename(String filename, String extension) {  
  70.         String fullFilename = filename + extension;  
  71.         if(!new File(fullFilename).exists()) {  
  72.             return fullFilename;  
  73.         }  
  74.           
  75.         filename = filename + FILENAME_SEQUENCE_SEPARATOR;  
  76.           
  77.         /* 
  78.          * This number is used to generate partially randomized filenames to avoid 
  79.          * collisions. 
  80.          * It starts at 1. 
  81.          * The next 9 iterations increment it by 1 at a time (up to 10). 
  82.          * The next 9 iterations increment it by 1 to 10 (random) at a time. 
  83.          * The next 9 iterations increment it by 1 to 100 (random) at a time. 
  84.          * ... Up to the point where it increases by 100000000 at a time. 
  85.          * (the maximum value that can be reached is 1000000000) 
  86.          * As soon as a number is reached that generates a filename that doesn't exist, 
  87.          *     that filename is used. 
  88.          * If the filename coming in is [base].[ext], the generated filenames are 
  89.          *     [base]-[sequence].[ext]. 
  90.          */  
  91.          int sequence = 1;  
  92.          for (int magnitude = 1; magnitude < 1000000000; magnitude *= 10) {  
  93.              for (int iteration = 0; iteration < 9; ++iteration) {  
  94.                  fullFilename = filename + sequence + extension;  
  95.                  if (!new File(fullFilename).exists()) {  
  96.                      return fullFilename;  
  97.                  }  
  98.                  Log.v(LOG, "file with sequence number " + sequence + " exists");  
  99.                  sequence += sRandom.nextInt(magnitude) + 1;  
  100.              }  
  101.          }  
  102.           
  103.         return fullFilename;  
  104.     }  
  105. }  

 

二、layout目录下的main.xml中的代码如下:

[html]  view plain copy print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_marginTop="20dip"  
  11.         android:gravity="center"  
  12.         android:text="@string/hello" />  
  13.   
  14.     <TextView  
  15.         android:id="@+id/text_view"  
  16.         android:layout_width="fill_parent"  
  17.         android:layout_height="wrap_content"  
  18.         android:layout_marginTop="20dip"  
  19.         android:text=""   
  20.         />  
  21.     <TextView  
  22.         android:id="@+id/text_view2"  
  23.         android:layout_width="fill_parent"  
  24.         android:layout_height="wrap_content"  
  25.         android:layout_marginTop="20dip"  
  26.         android:text="" />  
  27. </LinearLayout>  

 

三、values目录下的strings.xml中的代码:

[html]  view plain copy print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.   
  4.     <string name="hello">This is daming Original</string>  
  5.     <string name="app_name">CopyFileApp</string>  
  6.     <string name="download_sdcard_busy_dlg_title" product="default" msgid="6877712666046917741">"SD 卡不可用"</string>  
  7.     <string name="download_sdcard_busy_dlg_msg">"SD 卡正忙。要允许下载,请在通知中选择“关闭 USB 存储设备”。"</string>  
  8.     <string name="download_no_sdcard_dlg_msg" product="default" msgid="2616399456116301518">"需要有 SD 卡才能下载</string>  
  9.     <string name="download_no_sdcard_dlg_title" product="default" msgid="605904452159416792">"无 SD 卡"</string>  
  10.     <string name="cancel" msgid="3017274947407233702">"取消"</string>  
  11.     <string name="ok" msgid="1509280796718850364">"确定"</string>  
  12. </resources>  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值