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

标签 java file-io groovy

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

相关文章:

java - 检查字符串中是否存在重复字符

java - Jersey 两次序列化继承的属性(property)

java - JTextArea 与 JPanel 内的 JScrollPane 不能很好地配合

java - JFrame:单击按钮时如何隐藏主窗口?

ios - 第一次应用程序更新,用户数据丢失(存储在 Documents 目录中)

java - 在 Java 中逐行读取大型 JSON 文件的快速高效方法

file-io - Windows 中的 Dart 文件复制

grails - 如何在 grails 测试中比较 JSON

java - 集合继承java vs groovy

java - Groovy 无法运行类路径