Java, downloading files

k++

k++

Associate
Joined
5 Oct 2004
Posts
585
Location
London
I'm having trouble downloading a rather large text file using java, specifically this:

map.sql

Unfortunately when the file is downloaded I find it isn't complete, and infact the last 20 or so entries are missing :confused:

my code:

Code:
public void download(String address, String filePath) {
    try {
      URL url = new URL(address);
      URLConnection urlConnection = url.openConnection();
      urlConnection.connect();
      InputStream input = url.openStream();
      FileWriter fw = new FileWriter("map.txt");
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
      String tString = bufferedReader.readLine();
      while (tString != null) {
        fw.write(tString);
        tString = bufferedReader.readLine();
      }
    } catch(Exception exception) {
      exception.printStackTrace();
    }
  }

Any suggestions?
 
Last edited:
I'm suspecting it's something to do with file sizes, as I have found that printing to the terminal displays the whole file. :confused:

What on earth could be going on. I have used a code snippet from the web thinking it was my code so I am now using

Code:
public void download(String address, String filePath) {
    try { 
      URL url = new URL(address); 
      InputStream inputStream = url.openStream();
      FileWriter fileWriter = new FileWriter(filePath); 
      byte[] buf = new byte[1024]; 
      int len; 
      while((len = inputStream.read(buf)) > 0 ) { 
        for(int i = 0; i < len; i++) { 
          fileWriter.write((char)buf[i]);
        } 
      }  
      inputStream.close(); 
    }
    catch (MalformedURLException exception) {
      exception.printStackTrace();
    }
    catch (IOException exception) {
      System.err.println("File not found : " + address);
    } 
    finally {
      System.out.println("FINALLY");
    }
  }

Just slightly modified :p
 
I have taken to working with the file on the fly, it will do for what I'm trying to achieve. I wanted to create an archive of different versions so I could monitor changes. Still achievable though I guess.
 
Thanks for that Una, I'm off to bed now so I'll try tomorrow after work. I understand now what my problem was. :rolleyes:

goodnight

Karl
 
Back
Top Bottom