我想从互联网网址下载csv文件。 我已经尝试了一些我可以在网上找到并且无法下载的代码。
URL google = new URL("myurl");
ReadableByteChannel rbc = Channels.newChannel(google.openStream());
FileOutputStream fos = new FileOutputStream("C://excelsheet.csv");
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
此代码无效
我使用了这个功能,它也不起作用。
public stacvoid saveUrl(String filename, String urlString) throws MalformedURLException, IOException
{
BufferedInputStream in = null;
FileOutputStream fout = null;
try
{
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1)
{
fout.write(data, 0, count);
}
}
finally
{
if (in != null)
in.close();
if (fout != null)
fout.close();
}
}
我在我的网址上尝试了一个简单的输入流,但这也不起作用。
URL oracle = new URL("myurl");
URLConnection yc = oracle.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
现在,如果我输入任何其他网址,而不是myurl,bufferedreader会获取数据。 如果我在浏览器中输入myurl,我会弹出一个保存或下载csv文件。 所以问题不在于一个不正确的“myurl”
运行在“myurl”上的servelet /代码是否可能实际检查请求是否来自浏览器,然后才发送数据。
谢谢大家。使用httpclient,它适用于我。下载csv文件的代码,在本地保存,然后读取并解析所有令牌。
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("your url to download");
HttpResponse response = httpclient.execute(httpget);
System.out.println(response.getProtocolVersion());
System.out.println(response.getStatusLine().getStatusCode());
System.out.println(response.getStatusLine().getReasonPhrase());
System.out.println(response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
FileOutputStream fos = new java.io.FileOutputStream("C://excelsheet.csv");
entity.writeTo(fos);
fos.close();
}
//create BufferedReader to read csv file
BufferedReader br = new BufferedReader( new FileReader("C://excelsheet.csv"));
String strLine = "";
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
while( (strLine = br.readLine()) != null)
{
lineNumber++;
//break comma separated line using ","
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens())
{
//display csv values
tokenNumber++;
System.out.println("Line # " + lineNumber +
", Token # " + tokenNumber
+ ", Token : "+ st.nextToken());
}
//reset token number
tokenNumber = 0;
}
}
catch (Exception e) {
System.out.println("insdie the catch part");
System.out.println(e.toString());
}