androidファイルダウンロード!download!


Download.JAvaに入っているのはプログラムの本体で、utilパッケージに入っているのはいくつかの共通の方法で、FileUtils.JAvaはファイルの基本的な操作を入れています.HttpDownloader.JAvaではダウンロードの基本的な操作です.
第一歩:まずメインプログラムの部分を見てみましょう
package mars.download;

import mars.util.HttpDownloader;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Download extends Activity implements OnClickListener
{
	/** Called when the activity is first created. */
	private Button downloadTxtButton;
	private Button downloadMp3Button;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		findView();
	}

	public void findView()
	{
		downloadTxtButton = (Button) findViewById(R.id.downloadTxt);
		downloadTxtButton.setOnClickListener(this);

		downloadMp3Button = (Button) findViewById(R.id.downloadMp3);
		downloadMp3Button.setOnClickListener(this);
	}

	@Override
	public void onClick(View v)
	{
		// TODO Auto-generated method stub
		int viewId = v.getId();
		switch (viewId)
		{
		
		/**
		 *              ,          。
		 */
		case R.id.downloadTxt:
		{
			HttpDownloader httpDownloader = new HttpDownloader();
			String lrc = httpDownloader.downStr("http://61.184.100.229/");//     url      
			Log.e("@@@@", "downloadTxt: " + lrc);
		}
		
		/**
		 *             。
		 */
		case R.id.downloadMp3:
		{
			HttpDownloader httpDownloader = new HttpDownloader();
			int result = httpDownloader.downFile(
					"http://192.168.1.107:8080/voa1500/a1.mp3", "voa/",
					"a1.mp3");//     url        
			Log.e("@@@@", "downloadMp3");
		}
		default:
			break;
		}
	}
}

ステップ2:sdcardのファイルに対する基本的な操作を見てみましょう.
package mars.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;

public class FileUtils
{
	private String SDPATH;

	public String getSDPATH()
	{
		return SDPATH;
	}

	public FileUtils()
	{
		//    SDCARD        /SDCARD, Environment.getExternalStorageDirectory()        
		SDPATH = Environment.getExternalStorageDirectory() + "/";
	}

	/**
	 *  SD      
	 */
	public File creatSDFile(String fileName) throws IOException
	{
		File file = new File(SDPATH + fileName);
		file.createNewFile();
		return file;
	}

	/**
	 *  SD      
	 */
	public File creatSDDir(String dirName)
	{
		File dir = new File(SDPATH + dirName);
		dir.mkdir();
		return dir;
	}

	/**
	 *   SD          
	 */
	public boolean isFileExist(String fileName)
	{
		File file = new File(SDPATH + fileName);
		return file.exists();
	}

	/**
	 *    InputStream        SD  
	 */
	public File write2SDFromInput(String path, String fileName,
			InputStream input)
	{
		File file = null;
		OutputStream output = null;
		try//InputStream        SD       
		{
			creatSDDir(path);
			file = creatSDFile(path + fileName);
			output = new FileOutputStream(file);
			byte buffer[] = new byte[4 * 1024];
			while ((input.read(buffer)) != -1)
			{
				output.write(buffer);
			}
			output.flush();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				output.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		return file;
	}
}

ステップ3:ダウンロードの基本操作
package mars.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpDownloader
{
	/**
	 *   URL    ,               ,               
	 * 1.    URL  
	 * 2.  URL  ,    HttpURLConnection  
	 * 3.  InputStram
	 * 4. InputStream      
	 */
	private URL url = null;

	public String downStr(String urlStr)//        
	{
		/**
		 * String StringBuffer             ,             。
		 * String       ,        。 StringBuffer      ,             。 
		 */
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;//BufferedReader            

		try
		{
			/**
			 *       InputStream   ,     BufferedReader,             。
			 */
			
			url = new URL(urlStr);//     URL  		
			HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();//     Http  
			buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));//   IO     
			
			while ((line = buffer.readLine()) != null)
			{
				sb.append(line);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				buffer.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/**
	 *  -1:         
	 *   0:         
	 *   1:        
	 */
	public int downFile(String urlStr, String path, String fileName)//       
	{
		InputStream inputStream = null;
		try
		{
			FileUtils fileUtils = new FileUtils();

			if (fileUtils.isFileExist(path + fileName))
			{
				return 1;
			}
			else
			{
				inputStream = getInputStreamFromUrl(urlStr);
				File resultFile = fileUtils.write2SDFromInput(path, fileName,inputStream);
				if (resultFile == null)
				{
					return -1;
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return -1;
		}
		finally
		{
			try
			{
				inputStream.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		return 0;
	}

	/**
	 *   URL     
	 */
	public InputStream getInputStreamFromUrl(String urlStr)
			throws MalformedURLException, IOException
	{
		url = new URL(urlStr);//     URL  	
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();//     Http  
		InputStream inputStream = urlConn.getInputStream();//     
		
		return inputStream;
	}
}