Naming rules for repeated Android download files [Android source code parsing 7]

Source: Internet
Author: User

Question: A person cannot fall in two traps.

In February last April, I had a task that asked me to write a method for downloading and saving the file. If the file name exists, add "-1". If it still exists, add 1 to the number after-, for example: File Name: keep_on_it.mp3. the first download is keep_on_it.mp3, the second download name is saved as: Keep_On_It-1.mp3, the third download name is saved as: Keep_On_It-2.mp3, the fourth download name is saved as: Keep_On_It-3.mp3, and so on. At that time, I used a stupid method with poor readability. At that time, I used it for half a day and compared it by intercepting strings. Recently, When I downloaded the source code, I found that the for loop can be used for implementation. It is readable, easy to understand, and concise in algorithms. It is worthy of Google's design. It is simple, clear, and easy to understand.

Reprinted please indicate the source: http://blog.csdn.net/wdaming1986/article/details/7342559

Now, let's share with you the following:

If the directory of the memory card only contains these MP3 files:

The last keep_it_on-3.mp3 name is retained.

 

The code is provided below:

In the copyfileapp project:

I. Code in the copyfileappactivity. Java class under the com.cn. Daming. copyfile package:

package com.cn.daming.copyfile;import java.io.File;import java.util.Random;import android.app.Activity;import android.app.AlertDialog;import android.os.Bundle;import android.os.Environment;import android.os.SystemClock;import android.util.Log;import android.widget.TextView;public class CopyFileAppActivity extends Activity {    /** Called when the activity is first created. */private final static String SDCARD_PATH="/mnt/sdcard/download/mp3/Keep_It_On.mp3";private final static String FILENAME_SEQUENCE_SEPARATOR = "-";private static Random sRandom = new Random(SystemClock.uptimeMillis());private final static String LOG = "wangxianming";private TextView m_TextView;private TextView m_TextView_full;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                m_TextView = (TextView)findViewById(R.id.text_view);        m_TextView_full = (TextView)findViewById(R.id.text_view2);                Log.v(LOG, " ---->"+SystemClock.uptimeMillis());                // Check to see if we have an SDCard        String status = Environment.getExternalStorageState();        if (!status.equals(Environment.MEDIA_MOUNTED)) {            int title;            String msg;            // Check to see if the SDCard is busy, same as the music app            if (status.equals(Environment.MEDIA_SHARED)) {                msg = getString(R.string.download_sdcard_busy_dlg_msg);                title = R.string.download_sdcard_busy_dlg_title;            } else {                msg = getString(R.string.download_no_sdcard_dlg_msg, "no sdcard");                title = R.string.download_no_sdcard_dlg_title;            }            new AlertDialog.Builder(this)                .setTitle(title)                .setIcon(android.R.drawable.ic_dialog_alert)                .setMessage(msg)                .setPositiveButton(R.string.ok, null)                .show();            return;        }                File mp3File = new File(SDCARD_PATH);        if(mp3File != null && mp3File.exists()) {        String fileNamePath = mp3File.getAbsolutePath();        String filename = fileNamePath.substring(0, fileNamePath.lastIndexOf("."));        String extension = fileNamePath.substring(fileNamePath.lastIndexOf("."), fileNamePath.length());        m_TextView.setText(filename + extension);        m_TextView_full.setText(chooseUniqueFilename(filename, extension));        }    }        //This is method is core    private String chooseUniqueFilename(String filename, String extension) {    String fullFilename = filename + extension;    if(!new File(fullFilename).exists()) {    return fullFilename;    }        filename = filename + FILENAME_SEQUENCE_SEPARATOR;        /*         * This number is used to generate partially randomized filenames to avoid         * collisions.         * It starts at 1.         * The next 9 iterations increment it by 1 at a time (up to 10).         * The next 9 iterations increment it by 1 to 10 (random) at a time.         * The next 9 iterations increment it by 1 to 100 (random) at a time.         * ... Up to the point where it increases by 100000000 at a time.         * (the maximum value that can be reached is 1000000000)         * As soon as a number is reached that generates a filename that doesn't exist,         *     that filename is used.         * If the filename coming in is [base].[ext], the generated filenames are         *     [base]-[sequence].[ext].         */         int sequence = 1;         for (int magnitude = 1; magnitude < 1000000000; magnitude *= 10) {             for (int iteration = 0; iteration < 9; ++iteration) {                 fullFilename = filename + sequence + extension;                 if (!new File(fullFilename).exists()) {                     return fullFilename;                 }                 Log.v(LOG, "file with sequence number " + sequence + " exists");                 sequence += sRandom.nextInt(magnitude) + 1;             }         }        return fullFilename;    }}

 

II. The code in Main. xml under the layout directory is as follows:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginTop="20dip"        android:gravity="center"        android:text="@string/hello" />    <TextView        android:id="@+id/text_view"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginTop="20dip"        android:text=""         />    <TextView        android:id="@+id/text_view2"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginTop="20dip"        android:text="" /></LinearLayout>

 

Iii. Code in strings. xml under the values directory:

<? XML version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "hello"> This is Daming original </string> <string name = "app_name"> copyfileapp </string> <string name = "download_sdcard_busy_dlg_title" Product = "default" msgid = "6877712666046917741"> "SD card unavailable" </string> <string name = "download_sdcard_busy_dlg_msg"> "the SD card is busy. To allow download, select "Disable USB storage device" in the notification ". "</String> <string name =" download_no_sdcard_dlg_msg "Product =" default "msgid =" 2616399456116301518 ">" SD card required for download </string> <string name = "download_no_sdcard_dlg_title "Product =" default "msgid =" 605904452159416792 ">" No SD card "</string> <string name =" cancel "msgid =" 3017274947407233702 ">" cancel "</string> <string name = "OK" msgid = "1509280796718850364"> "OK" </string> </resources>

If you have any good suggestions or novel ideas, please leave a message. You are welcome to discuss them together .......

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.