我一直在想如何将这个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/