B
ByteCoder
I just created the code below to download a file from a URL. Text/HTML
files work fine, but images don't show up properly in an image viewer.
The weird thing is that the correct number of bytes (from the google
logo) are counted. OutputStreamWriter is flushed etc.
I think it's some sort of byte to int conversion problem, but I have no
idea how to do this differently.
Any help would be greatly appreciated!
---working method:---
private void downloadURL() {
try {
// Create the URL
URL u = new URL
("http://www.google.com/intl/en/images/logo.gif");
// Save the file the URL points to to this file
File file = new File(System.getProperty("user.home") +
File.separator + "logo.gif");
// Create a connection with the URL
InputStream input = u.openStream();
input = new BufferedInputStream(input);
Reader reader = new InputStreamReader(input);
// Create the OutputStream and Writer
FileOutputStream output = new FileOutputStream(file);
Writer writer = new OutputStreamWriter(output);
// Write the received bytes to the file.
int numberOfBytes = 0;
int c;
while((c = reader.read()) != -1) {
writer.write(c);
numberOfBytes++;
}
System.out.println("File size: " + numberOfBytes + " byte
(s).");
// Flush the writer!
writer.flush();
// Close connections.
reader.close();
writer.close();
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
}
---end working method---
files work fine, but images don't show up properly in an image viewer.
The weird thing is that the correct number of bytes (from the google
logo) are counted. OutputStreamWriter is flushed etc.
I think it's some sort of byte to int conversion problem, but I have no
idea how to do this differently.
Any help would be greatly appreciated!
---working method:---
private void downloadURL() {
try {
// Create the URL
URL u = new URL
("http://www.google.com/intl/en/images/logo.gif");
// Save the file the URL points to to this file
File file = new File(System.getProperty("user.home") +
File.separator + "logo.gif");
// Create a connection with the URL
InputStream input = u.openStream();
input = new BufferedInputStream(input);
Reader reader = new InputStreamReader(input);
// Create the OutputStream and Writer
FileOutputStream output = new FileOutputStream(file);
Writer writer = new OutputStreamWriter(output);
// Write the received bytes to the file.
int numberOfBytes = 0;
int c;
while((c = reader.read()) != -1) {
writer.write(c);
numberOfBytes++;
}
System.out.println("File size: " + numberOfBytes + " byte
(s).");
// Flush the writer!
writer.flush();
// Close connections.
reader.close();
writer.close();
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
}
---end working method---