日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

java远程下载文件到本地_java远程下载文件到本地

發布時間:2024/10/8 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java远程下载文件到本地_java远程下载文件到本地 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

方法一

**

* 下載遠程文件并保存到本地

*

* @param remoteFilePath-遠程文件路徑

* @param localFilePath-本地文件路徑(帶文件名)

*/

public void downloadFile(String remoteFilePath, String localFilePath) {

URL urlfile = null;

HttpURLConnection httpUrl = null;

BufferedInputStream bis = null;

BufferedOutputStream bos = null;

File f = new File(localFilePath);

try {

urlfile = new URL(remoteFilePath);

httpUrl = (HttpURLConnection) urlfile.openConnection();

httpUrl.connect();

bis = new BufferedInputStream(httpUrl.getInputStream());

bos = new BufferedOutputStream(new FileOutputStream(f));

int len = 2048;

byte[] b = new byte[len];

while ((len = bis.read(b)) != -1) {

bos.write(b, 0, len);

}

bos.flush();

bis.close();

httpUrl.disconnect();

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

bis.close();

bos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

方法二

/**

* 下載遠程文件并保存到本地

*

* @param remoteFilePath-遠程文件路徑

* @param localFilePath-本地文件路徑(帶文件名)

*/

public void downloadFile(String remoteFilePath, String localFilePath) {

URL website = null;

ReadableByteChannel rbc = null;

FileOutputStream fos = null;

try {

website = new URL(remoteFilePath);

rbc = Channels.newChannel(website.openStream());

fos = new FileOutputStream(localFilePath);//本地要存儲的文件地址 例如:test.txt

fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

} catch (Exception e) {

e.printStackTrace();

}finally{

if(fos!=null){

try {

fos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if(rbc!=null){

try {

rbc.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

總結

以上是生活随笔為你收集整理的java远程下载文件到本地_java远程下载文件到本地的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。