在android中下载文件(从本地系统)获取错误

时间:2013-02-19 14:47:48

标签: android

Download.java

package com.example.download_file;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import android.os.Bundle;

import android.os.Environment;

import android.app.Activity;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

public class Download extends Activity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_download);

       final Button downloadbutton=(Button)findViewById(R.id.download_button);

       final  EditText text=(EditText)findViewById(R.id.download_filename);

       downloadbutton.setOnClickListener(new OnClickListener()

 {


            @Override

            public void onClick(View v)
 {

       download();

       text.setText("success");

    }

       });

    }

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.activity_download, menu);

        download();

        return true;

    }

   public void download()

    {

        final  EditText text=(EditText)findViewById(R.id.download_filename);

        final  EditText localname=(EditText)findViewById(R.id.localname);

    try {

        String name=text.getText().toString();

        String sdcardname=localname.getText().toString();

        URL url = new URL(name);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();


        urlConnection.setRequestMethod("GET");

        urlConnection.setDoOutput(true);


        urlConnection.connect();


        File SDCardRoot = Environment.getExternalStorageDirectory();


        File file = new File(SDCardRoot,sdcardname);


        FileOutputStream fileOutput = new FileOutputStream(file);

        InputStream inputStream = urlConnection.getInputStream();


        int totalSize = urlConnection.getContentLength();

        int downloadedSize = 0;

     .
        byte[] buffer = new byte[1024];

        int bufferLength = 0;  

        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {

            fileOutput.write(buffer, 0, bufferLength);




        }


        fileOutput.close();


    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

    }

}

1)

输入:url =“\ 192.168.0.103 \ shared \ file.txt”

错误:java.net.MalformedURLException:找不到协议:\ 192.168.0.103 \ shared \ file.txt

2)

输入:url =“file://192.168.0.103/shared/file.txt”

错误:java.lang.ClassCastEXception:org.apache.harmony.luni.internal.net.www.protocol.ftp.FtpURLConnection

1 个答案:

答案 0 :(得分:0)

使用AsyncTask请看一下:链接AsyncTask可能会帮助您解决问题。