当前位置: 代码迷 >> Android >> Android 上载文件及写入SD卡
  详细解决方案

Android 上载文件及写入SD卡

热度:41   发布时间:2016-05-01 16:17:50.0
Android 下载文件及写入SD卡

Android 下载文件及写入SD卡,实例代码

?

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><Button  	android:id="@+id/downloadTxt"    android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="下载文本文件"    /><Button  	android:id="@+id/downloadMp3"    android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="下载MP3文件"    /></LinearLayout>

?

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.learning.example"      android:versionCode="1"      android:versionName="1.0">    <application android:icon="@drawable/icon" android:label="@string/app_name">        <activity android:name=".Download"                  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>    <uses-sdk android:minSdkVersion="8" /><!-- 访问网络和操作SD卡 加入的两个权限配置--><uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/></manifest> 

?

package com.learning.example.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 {		private URL url = null; 		/**	 * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本当中的内容	 * 1.创建一个URL对象	 * 2.通过URL对象,创建一个HttpURLConnection对象	 * 3.得到InputStream	 * 4.从InputStream当中读取数据	 * @param urlStr	 * @return	 */	public String download(String urlStr){		StringBuffer sb = new StringBuffer();		String line = null;		BufferedReader buffer = null;		try {			url = new URL(urlStr);			HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();			buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));			while( (line = buffer.readLine()) != null){				sb.append(line);			}					} 		catch (Exception e) {			e.printStackTrace();		}		finally{			try {				buffer.close();			} catch (IOException e) {				e.printStackTrace();			}		}		return sb.toString();	}	/**	 * 	 * @param urlStr	 * @param path	 * @param fileName	 * @return 	 * 		-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 (IOException e) {				e.printStackTrace();			}		}		return 0;	}		/**	 * 根据URL得到输入流	 * @param urlStr	 * @return	 */	public InputStream getInputStreamFromURL(String urlStr) {		HttpURLConnection urlConn = null;		InputStream inputStream = null;		try {			url = new URL(urlStr);			urlConn = (HttpURLConnection)url.openConnection();			inputStream = urlConn.getInputStream();					} catch (MalformedURLException e) {			e.printStackTrace();		} catch (IOException e) {			e.printStackTrace();		}				return inputStream;	}}

?

package com.learning.example.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;		private int FILESIZE = 4 * 1024; 		public String getSDPATH(){		return SDPATH;	}		public FileUtils(){		//得到当前外部存储设备的目录( /SDCARD )		SDPATH = Environment.getExternalStorageDirectory() + "/";	}		/**	 * 在SD卡上创建文件	 * @param fileName	 * @return	 * @throws IOException	 */	public File createSDFile(String fileName) throws IOException{		File file = new File(SDPATH + fileName);		file.createNewFile();		return file;	}		/**	 * 在SD卡上创建目录	 * @param dirName	 * @return	 */	public File createSDDir(String dirName){		File dir = new File(SDPATH + dirName);		dir.mkdir();		return dir;	}		/**	 * 判断SD卡上的文件夹是否存在	 * @param fileName	 * @return	 */	public boolean isFileExist(String fileName){		File file = new File(SDPATH + fileName);		return file.exists();	}		/**	 * 将一个InputStream里面的数据写入到SD卡中	 * @param path	 * @param fileName	 * @param input	 * @return	 */	public File write2SDFromInput(String path,String fileName,InputStream input){		File file = null;		OutputStream output = null;		try {			createSDDir(path);			file = createSDFile(path + fileName);			output = new FileOutputStream(file);			byte[] buffer = new byte[FILESIZE];			while((input.read(buffer)) != -1){				output.write(buffer);			}			output.flush();		} 		catch (Exception e) {			e.printStackTrace();		}		finally{			try {				output.close();			} catch (IOException e) {				e.printStackTrace();			}		}		return file;	}}

?

package com.learning.example;import com.learning.example.util.HttpDownloader;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class Download extends Activity {	private Button downlaodTxtButton ;	private Button downlaodMP3Button ;	    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        downlaodTxtButton = (Button)findViewById(R.id.downloadTxt);        downlaodTxtButton.setOnClickListener(new DownloadTxtListener());                downlaodMP3Button = (Button)findViewById(R.id.downloadMp3);        downlaodMP3Button.setOnClickListener(new DownloadMP3Listener());    }        class DownloadTxtListener implements OnClickListener{		@Override		public void onClick(View v) {			HttpDownloader downloader = new HttpDownloader();			String lrc = downloader.download("http://172.16.11.9:8080/test/1.lrc");			System.out.println(lrc);		}    	    }        class DownloadMP3Listener implements OnClickListener{		@Override		public void onClick(View v) {			HttpDownloader downloader = new HttpDownloader();			int result = downloader.downFile("http://172.16.11.9:8080/test/1.mp3", "voa/", "1.map3");			System.out.println(result);		}    	    }}

Notice:访问网络和操作SD卡 记得加入的两个权限配置

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

1 楼 tiantianhappy 2011-02-10  
你好,请教一个问题,我和你写的代码一摸一样,可是我的运行总是报错,错误如下:
02-10 11:50:46.118: ERROR/vold(27): Error opening switch name path '/sys/class/switch/test2' (No such file or directory)
02-10 11:50:46.118: ERROR/vold(27): Error bootstrapping switch '/sys/class/switch/test2' (No such file or directory)
02-10 11:50:46.118: ERROR/vold(27): Error opening switch name path '/sys/class/switch/test' (No such file or directory)
02-10 11:50:46.118: ERROR/vold(27): Error bootstrapping switch '/sys/class/switch/test' (No such file or directory)
02-10 11:50:55.977: ERROR/MemoryHeapBase(51): error opening /dev/pmem: No such file or directory
02-10 11:50:55.977: ERROR/SurfaceFlinger(51): Couldn't open /sys/power/wait_for_fb_sleep or /sys/power/wait_for_fb_wake
02-10 11:50:56.077: ERROR/libEGL(51): couldn't load <libhgl.so> library (Cannot load library: load_library[984]: Library 'libhgl.so' not found)
02-10 11:50:56.507: ERROR/libEGL(62): couldn't load <libhgl.so> library (Cannot load library: load_library[984]: Library 'libhgl.so' not found)
02-10 11:50:58.998: ERROR/BatteryService(51): Could not open '/sys/class/power_supply/usb/online'
02-10 11:50:59.008: ERROR/BatteryService(51): Could not open '/sys/class/power_supply/battery/batt_vol'
02-10 11:50:59.008: ERROR/BatteryService(51): Could not open '/sys/class/power_supply/battery/batt_temp'
02-10 11:50:59.498: ERROR/EventHub(51): could not get driver version for /dev/input/mouse0, Not a typewriter
02-10 11:50:59.498: ERROR/EventHub(51): could not get driver version for /dev/input/mice, Not a typewriter
02-10 11:50:59.747: ERROR/System(51): Failure starting core service
02-10 11:50:59.747: ERROR/System(51): java.lang.SecurityException
02-10 11:50:59.747: ERROR/System(51):     at android.os.BinderProxy.transact(Native Method)
02-10 11:50:59.747: ERROR/System(51):     at android.os.ServiceManagerProxy.addService(ServiceManagerNative.java:146)
02-10 11:50:59.747: ERROR/System(51):     at android.os.ServiceManager.addService(ServiceManager.java:72)
02-10 11:50:59.747: ERROR/System(51):     at com.android.server.ServerThread.run(SystemServer.java:162)
02-10 11:50:59.757: ERROR/AndroidRuntime(51): Crash logging skipped, no checkin service
02-10 11:51:00.798: ERROR/LockPatternKeyguardView(51): Failed to bind to GLS while checking for account
02-10 11:51:03.998: ERROR/ActivityThread(93): Failed to find provider info for com.google.settings
02-10 11:51:03.998: ERROR/ActivityThread(93): Failed to find provider info for com.google.settings
02-10 11:51:06.267: ERROR/ApplicationContext(51): Couldn't create directory for SharedPreferences file shared_prefs/wallpaper-hints.xml
02-10 11:51:14.297: ERROR/MediaPlayerService(31): Couldn't open fd for content://settings/system/notification_sound
02-10 11:51:14.328: ERROR/MediaPlayer(51): Unable to to create media player
02-10 11:51:08.398: ERROR/ActivityThread(91): Failed to find provider info for android.server.checkin
02-10 11:51:10.668: ERROR/ActivityThread(91): Failed to find provider info for android.server.checkin
02-10 11:51:10.887: ERROR/ActivityThread(91): Failed to find provider info for android.server.checkin
02-10 11:57:08.328: ERROR/AndroidRuntime(224): Uncaught handler: thread main exiting due to uncaught exception
02-10 11:57:08.338: ERROR/AndroidRuntime(224): java.lang.NullPointerException
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at com.wjl.HttpDownLoader.download(HttpDownLoader.java:53)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at com.wjl.DownLoadActivity$DownLoadTextListener.onClick(DownLoadActivity.java:33)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.view.View.performClick(View.java:2344)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.view.View.onTouchEvent(View.java:4133)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.widget.TextView.onTouchEvent(TextView.java:6510)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.view.View.dispatchTouchEvent(View.java:3672)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1712)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1202)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.app.Activity.dispatchTouchEvent(Activity.java:1987)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1696)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1658)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.os.Looper.loop(Looper.java:123)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at android.app.ActivityThread.main(ActivityThread.java:4203)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at java.lang.reflect.Method.invokeNative(Native Method)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at java.lang.reflect.Method.invoke(Method.java:521)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
02-10 11:57:08.338: ERROR/AndroidRuntime(224):     at dalvik.system.NativeStart.main(Native Method)

我实在是不知道那里错了,请您帮忙解决一下,万分感谢。
2 楼 zjx2388 2011-02-14  
tiantianhappy 写道
你好,请教一个问题,我和你写的代码一摸一样,可是我的运行总是报错,错误如下:
02-10 11:50:46.118: ERROR/vold(27): Error opening switch name path '/sys/class/switch/test2' (No such file or directory)
02-10 11:50:46.118: ERROR/vold(27): Error bootstrapping switch '/sys/class/switch/test2' (No such file or directory)
02-10 11:50:46.118: ERROR/vold(27): Error opening switch name path '/sys/class/switch/test' (No such file or directory)
02-10 11:50:46.118: ERROR/vold(27): Error bootstrapping switch '/sys/class/switch/test' (No such file or directory)
02-10 11:50:55.977: ERROR/MemoryHeapBase(51): error opening /dev/pmem: No such file or directory
02-10 11:50:55.977: ERROR/SurfaceFlinger(51): Couldn't open /sys/power/wait_for_fb_sleep or /sys/power/wait_for_fb_wake
...

你是在手机真机上测试的,还是模拟器,报错是没有找到文件,你必需先有能下载的文件才行.
3 楼 jackqdyulei 2011-03-06  
这段代码有点小错误~
public int downFile(String urlStr, String path, String fileName) 函数中,如果文件已存在,会直接return 1并跳转到finally语句(注意此时 inputStream=null),执行 inputStream.close()时会发生空指针引用错误但却没有catch,因此需要多加一个catch语句~
4 楼 zjx2388 2011-03-07  
jackqdyulei 写道
这段代码有点小错误~
public int downFile(String urlStr, String path, String fileName) 函数中,如果文件已存在,会直接return 1并跳转到finally语句(注意此时 inputStream=null),执行 inputStream.close()时会发生空指针引用错误但却没有catch,因此需要多加一个catch语句~



谢谢
5 楼 tiantianhappy 2011-03-21  
zjx2388 写道
tiantianhappy 写道
你好,请教一个问题,我和你写的代码一摸一样,可是我的运行总是报错,错误如下:
02-10 11:50:46.118: ERROR/vold(27): Error opening switch name path '/sys/class/switch/test2' (No such file or directory)
02-10 11:50:46.118: ERROR/vold(27): Error bootstrapping switch '/sys/class/switch/test2' (No such file or directory)
02-10 11:50:46.118: ERROR/vold(27): Error opening switch name path '/sys/class/switch/test' (No such file or directory)
02-10 11:50:46.118: ERROR/vold(27): Error bootstrapping switch '/sys/class/switch/test' (No such file or directory)
02-10 11:50:55.977: ERROR/MemoryHeapBase(51): error opening /dev/pmem: No such file or directory
02-10 11:50:55.977: ERROR/SurfaceFlinger(51): Couldn't open /sys/power/wait_for_fb_sleep or /sys/power/wait_for_fb_wake
...

你是在手机真机上测试的,还是模拟器,报错是没有找到文件,你必需先有能下载的文件才行.

谢谢,问题解决了。就是因为找不到文件
6 楼 renwolang521 2011-03-30  
private int FILESIZE = 4 * 1024; byte[] buffer = new byte[FILESIZE];  while((input.read(buffer)) != -1){      output.write(buffer);  }  output.flush();

作者 这些 有没有试过呢?
这段代码 难道没有问题吗?
将流读入buffer的时候,通常是读多少length,写多少length,对吧?
你这样下载下来的mp3能 播放吗?
7 楼 zjx2388 2011-03-31  
renwolang521 写道
private int FILESIZE = 4 * 1024; byte[] buffer = new byte[FILESIZE];  while((input.read(buffer)) != -1){      output.write(buffer);  }  output.flush();

作者 这些 有没有试过呢?
这段代码 难道没有问题吗?
将流读入buffer的时候,通常是读多少length,写多少length,对吧?
你这样下载下来的mp3能 播放吗?



测试过的,能播放,不过是在模拟器上,没在真机测试这个

你如果觉得不对,如果方便,请上传你的代码,谢谢!
8 楼 tscfengkui 2011-08-30  
可能你的模拟器上没有sdcard原因造成的 ,设置模拟器的size就会出现sdcard
9 楼 菜刀闯天下 2011-09-08  
tscfengkui 写道
可能你的模拟器上没有sdcard原因造成的 ,设置模拟器的size就会出现sdcard

  thanks   问题解决
10 楼 zdfeng 2011-10-09  
我喜欢,java看着就是爽,虽然是android,基础,还是java。好风格,好作者。
  相关解决方案