Android:最简单的网址下载没有进度条

时间:2015-07-05 23:48:34

标签: java android http downloading

我曾尝试为Android java实现10-15种不同的下载机制,但我根本无法成功。 我不关心进度条或后台进程。 我只想要尽可能少的一行功能下载代码 我希望它将二进制文件(前台)下载到设备中可以作为

访问的目录
File pf = new File("filename");
if (pf.exists())  { ... }

1 个答案:

答案 0 :(得分:0)

试试这个(从here修改):

try {
        URL url = new URL("http://url.com");

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

        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();

        //THIS IS WHERE YOU GET THE DIRECTORY TO SAVE TO
        File SDCardRoot = Environment.getExternalStorageDirectory();
        //THIS IS WHERE YOU WILL SET THE FILE NAME
        File file = new File(SDCardRoot,"somefile.txt");

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();

        //create a buffer...
        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();
}

您可能还需要添加访问电话簿的权限:

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

有关访问内部目录中某些文件夹的信息,请参阅android开发者页面:http://developer.android.com/training/basics/data-storage/files.html#WriteInternalStorage

事实上,该页面上的解决方案也很短:

String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;

try {
  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
  outputStream.write(string.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}