Java怎么通过远程读取流的方式将远程文件放到本地

Python016

Java怎么通过远程读取流的方式将远程文件放到本地,第1张

以下回答为本人意见,如果有误还请见谅。

java获取远程文件的方式在我的开发过程中使用过两种

1。通过http请求进行静态资源,首先确定文件的URL地址,然后通过URLConnection进行连接,然后通过读取连接中返回的InputStream,再通过文件输出流FileOutputStream进行存储(下载)。

2.通过FTP或SFTP进行远程文件的下载,具体实现有很多第三方的包,百度即可。

strUrl为文件地址,fileName为文件在本地的保存路径,试试吧~

public static void writeFile(String strUrl, String fileName) {

URL url = null

try {

url = new URL(strUrl)

} catch (MalformedURLException e2) {

e2.printStackTrace()

}

InputStream is = null

try {

is = url.openStream()

} catch (IOException e1) {

e1.printStackTrace()

}

OutputStream os = null

try {

os = new FileOutputStream( fileName)

int bytesRead = 0

byte[] buffer = new byte[8192]

while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {

os.write(buffer, 0, bytesRead)

}

System.out.println("下载成功:"+strUrl)

} catch (FileNotFoundException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

}

}