我在从我的应用程序中下载二进制文件(视频)时遇到问题.在Quicktime中,如果我直接下载它可以正常工作但通过我的应用程序不知何故它搞砸了(即使它们在文本编辑器中看起来完全相同).这是一个例子:
URL u = new URL("http://www.path.to/a.mp4?video"); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); FileOutputStream f = new FileOutputStream(new File(root,"Video.mp4")); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; while ( (len1 = in.read(buffer)) > 0 ) { f.write(buffer); } f.close();
Ry4an Brase.. 93
我不知道这是否是唯一的问题,但是你有一个经典的Java故障:你并不指望read()总是被允许返回比你要求的更少的字节.因此,您的读取可能少于1024个字节,但您的写入总是写出1024个字节,可能包括前一个循环迭代的字节.
纠正:
while ( (len1 = in.read(buffer)) > 0 ) { f.write(buffer,0, len1); }
也许Android上更高延迟的网络或更小的3G数据包大小会加剧这种影响?
我不知道这是否是唯一的问题,但是你有一个经典的Java故障:你并不指望read()总是被允许返回比你要求的更少的字节.因此,您的读取可能少于1024个字节,但您的写入总是写出1024个字节,可能包括前一个循环迭代的字节.
纠正:
while ( (len1 = in.read(buffer)) > 0 ) { f.write(buffer,0, len1); }
也许Android上更高延迟的网络或更小的3G数据包大小会加剧这种影响?
new DefaultHttpClient().execute(new HttpGet("http://www.path.to/a.mp4?video")) .getEntity().writeTo( new FileOutputStream(new File(root,"Video.mp4")));
一个问题是你读取缓冲区.如果输入流的每次读取都不是1024的精确倍数,则会复制错误数据.使用:
byte[] buffer = new byte[1024]; int len1 = 0; while ( (len1 = in.read(buffer)) != -1 ) { f.write(buffer,0, len1); }
public class download extends Activity { private static String fileName = "file.3gp"; private static final String MY_URL = "Your download url goes here"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { URL url = new URL(MY_URL); HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); String PATH = Environment.getExternalStorageDirectory() + "/download/"; Log.d("Abhan", "PATH: " + PATH); File file = new File(PATH); if(!file.exists()) { file.mkdirs(); } File outputFile = new File(file, fileName); FileOutputStream fos = new FileOutputStream(outputFile); InputStream is = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; while ((len1 = is.read(buffer)) != -1) { fos.write(buffer, 0, len1); } fos.flush(); fos.close(); is.close(); } catch (IOException e) { Log.e("Abhan", "Error: " + e); } Log.i("Abhan", "Check Your File."); } }