使用 Java 以编程方式下载 CSV 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4120942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically Downloading CSV Files with Java
提问by javacavaj
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.
场景:我用来研究股票数据的网站在页面上有一个将数据导出到电子表格的链接。将鼠标悬停在导出链接上时显示的 URL 的格式为http://www.stocksite.com/historical/export.php?symbol=C。
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.
问题:相反,我希望手动访问每只股票的页面来自动执行任务。在 Java 中,如何以编程方式调用带有股票代码的站点并保存导出的 csv 文件?URL 和 URLConnection 类似乎是显而易见的起点,但我不确定从哪里开始。
回答by BalusC
All you need to do is to get the CSV in flavor of an InputStream
.
您需要做的就是获取 .csv 格式的 CSV 文件InputStream
。
InputStream input = new URL("http://example.com/file.csv").openStream();
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.
然后你可以将它提供给任何像样的Java CSV 解析器 API。几乎他们中的任何一个都以InputStream
or 的风格进行输入Reader
。如有必要,您可以轻松地将其装饰InputStream
为Reader
使用InputStreamReader
,然后您可以将其提供给 CSV 解析器。
Reader reader = new InputStreamReader(input, "UTF-8");