使用Java以编程方式下载CSV文件
场景:我用来研究股票数据的网站在页面上有一个链接,用于将数据导出到电子表格.将鼠标悬停在导出链接上时显示的URL格式为 http://www.stocksite.com/historical/export.php?symbol=C .
Scenario: A website I use to research stock data has a link on the page to Export Data to Spreadsheet. The URL displayed when hovering over the export link is of the form http://www.stocksite.com/historical/export.php?symbol=C .
问题:而是手动访问每个股票的页面,我想使任务自动化.从Java中,我如何以程序代码调用带有股票代号的网站并保存导出的csv文件?URL和URLConnection类似乎是一个显而易见的起点,但是我不确定从那里开始.
Question: Rather, that manually visiting the page for each stock I would like to automate the task. From Java, how can I programmatically call the site with a stock symbol and save the exported csv file? The URL and URLConnection class seem like the obvious place to start, but I'm unsure where to go from there.
所有您需要做的就是获取具有 InputStream
风格的CSV.
All you need to do is to get the CSV in flavor of an InputStream
.
InputStream input = new URL("http://example.com/file.csv").openStream();
然后,您可以将其提供给任何体面的 Java CSV解析器API 一个>.他们中几乎任何一个都以 InputStream
或 Reader
的形式进行输入.如有必要,您可以使用 Reader
/io/InputStreamReader.html"rel =" noreferrer> InputStreamReader
Then you can feed it to any decent Java CSV parser API. Almost any of them take input in flavor of InputStream
or Reader
. If necessary, you can easily decorate InputStream
as a Reader
using InputStreamReader
which you can then feed to the CSV parser.
Reader reader = new InputStreamReader(input, "UTF-8");