djangofan
djangofan

Reputation: 29669

Convert this FileOutputStream Groovy method into pure Java?

I have been trying to think of how to convert this Groovy method into a pure Java method. Anyone want to take a stab at it?

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

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

The answer, thanks to tim_yates, turned out to be:

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() ;
    }
}

Upvotes: 1

Views: 1611

Answers (2)

Ray Tayek
Ray Tayek

Reputation: 10003

import java.io.*;
import java.net.*;
public class Jwget{
    public void wget(String urlstring,File destfile) throws Exception {
        URL url=new URL(urlstring);
        InputStream is=url.openStream();
        OutputStream os=new FileOutputStream(destfile);
        for(int i=is.read();i!=-1;i=is.read())
            os.write(i);
        is.close();
        os.close();
    }
    public static void main(String[] args) throws Exception {
        new Jwget().wget("http://tayek.com",new File("java.txt"));
    }
}

Upvotes: 0

tim_yates
tim_yates

Reputation: 171104

How about

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() ;
  }
}

I believe that should work... But I haven't tried it :-/

Upvotes: 1

Related Questions