0

Possible Duplicate:
Reading binary file from URLConnection

Now I have a URL:

(http://elsa.berkeley.edu/~saez/TabFig2005prel.xls for example, with http: scheme).

I need to access to this file and store it as a File object in my program so I can do my following work. So anyone knows how to make this to a File object? I have no idea how to covert a InputStream to a File.

Thank you Allan

Community
  • 1
  • 1
Allan Jiang
  • 11,063
  • 27
  • 104
  • 165

5 Answers5

1

How about using apache commons-io (http://commons.apache.org/io/)

It has a

FileUtils.copyURLToFile(URL,File);
andypandy
  • 1,117
  • 7
  • 9
1
int chunkSize = 500;

    BufferedInputStream in = new java.io.BufferedInputStream(new URL("http://javakata6425.appspot.com/db_imgs/projectsBinaries/photoLib/photoLib.jar").openStream());
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("d://temp//photoLib.jar"), chunkSize);
    byte[] data = new byte[chunkSize];
    int x = 0;
    while ((x = in.read(data, 0, chunkSize)) >= 0) {
        out.write(data, 0, x);
    }
    out.close();
    in.close();
Shivan Dragon
  • 15,004
  • 9
  • 62
  • 103
1

You can use the following code (assuming the InputStream object name is "content")

File myFile = new File("newFile.ext");
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(myFile);
    int read = 0;
    byte[] buff = new byte[1024];
    while ((read = content.read(buff)) > -1)
        fos.write(buff, 0, read);
} catch (IOException e1) {
    /* do something? */
} finally {
    if (fos != null) {
        try { fos.close() } catch (IOException e2) {/* do something? */}
    }
}
Udi Cohen
  • 1,259
  • 9
  • 12
1
URL url = new URL("http://elsa.berkeley.edu/~saez/TabFig2005prel.xls");
InputStream in = url.openStream();
try {
    OutputStream out = new FileOutputStream("output.xls");
    try {
        byte buf[] = new byte[4096];
        for (int n = in.read(buf); n > 0; n = in.read(buf)) {
            out.write(buf, 0, n);
        }
    } finally {
        out.close();
    }
} finally {
    in.close();
}
Maurice Perry
  • 32,610
  • 9
  • 70
  • 97
0

pseudocode:

create FileWriter pointing to "localdrive/local_copy.xls"
foreach byte you can read from the input stream:
    write the byte to the filewriter
flush the filewriter
close the filewriter

voila. You now have the file saved locally.

mcfinnigan
  • 11,442
  • 35
  • 28