Search code examples
javafiledownloadyahoo-finance

How to save a file to a certain folder which was downloaded in a rest URL request?


I am using Yahoo's URL request ability to download stock data. I have found a java application that downloads the data every 5 seconds. I cant figure out how one would go about downloading stock data to a certain folder in ones computer while using the basic code I have used in the application. There has been other posts about how to save yahoo URL request data to a certain location but it does not use the same code format that I'm using. All ideas, source code, and links explaining how I should do this would be very helpful. Thank you for your help!

My code:

import java.awt.Desktop;
import java.net.URL;

public class Downloader {

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            Thread.sleep(5000);
            try {
                Desktop.getDesktop()
                        .browse(new URL(
                                "http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=nab")
                                .toURI());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

Solution

  • you could use Java's IO capabilities, Are you trying to write a GUI, if not any specific reason to use AWT's Desktop class?

    Try this sample code:

    URL yahooFinance = new URL("http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=nab");
    ReadableByteChannel channel = Channels.newChannel(yahooFinance.openStream());
    FileOutputStream fos = new FileOutputStream("quotes.csv");
    fos.getChannel().transferFrom(channel, 0, Long.MAX_VALUE);