gpt4 book ai didi

java - 将这个 FileOutputStream Groovy 方法转换为纯 Java?

转载 作者:太空宇宙 更新时间:2023-11-04 08:35:59 24 4
gpt4 key购买 nike

我一直在想如何将这个Groovy方法转换成纯Java方法。有人想尝试一下吗?

public void wget(String urlstring, File destfile) {
new FileOutputStream(destfile).withStream{ out ->
new URL(urlstring).openStream().eachByte{
out.write(it)
}
}
}

----------------------------------------

感谢 tim_yates,答案是:

public void wget(String urlstring, File destfile) throws IOException {
InputStream bis = new URL( urlstring ).openStream() ;
BufferedOutputStream fos =
new BufferedOutputStream( new FileOutputStream( destfile ) ) ;
try {
byte[] buffer = new byte[ 2048 ] ;
@SuppressWarnings("unused")
int cnt=0;
while( ( cnt = bis.read( buffer, 0, 2048 ) ) > -1 ) {
fos.write( buffer, 0, 2048 ) ;
}
}
finally {
bis.close() ;
fos.close() ;
}
}

最佳答案

怎么样

public void wget( String urlstring, File destFile ) throws IOException {
BufferedInputStream bis = new URL( urlstring ).openStream() ;
BufferedOutputStream fos = new BufferedOutputStream( new FileOutputStream( destFile ) ) ;
try {
byte[] buffer = new byte[ 8192 ] ;
int cnt = 0 ;
while( ( cnt = bis.read( buffer, 0, 8192 ) ) > -1 ) {
fos.write( buffer, 0, 8192 ) ;
}
}
finally {
bis.close() ;
fos.close() ;
}
}

相信应该有效...但我还没有尝试过:-/

关于java - 将这个 FileOutputStream Groovy 方法转换为纯 Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6419597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com