我想從互聯網網址下載csv文件。 我已經嘗試了我可以在網上找到並且無法下載的所有代碼。無法從java下載網絡文件中的url
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,如果我輸入任何其他url,bufferedreader確實會獲取數據。 如果我在瀏覽器中輸入myurl,我會彈出一個窗口來保存或下載csv文件。 所以問題不在於不正確的「myurl」
「myurl」上運行的servlet /代碼是否有可能實際檢查請求是否來自瀏覽器,然後才發送數據。
謝謝大家。使用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());
}
如果您未登錄到網站,您是否可以使用瀏覽器訪問該文件? – 2012-04-25 19:28:21
什麼不適用'Channels',你會得到一個異常嗎?您可能沒有對C驅動器根目錄的寫權限。 – tenorsax 2012-04-25 19:35:54
Meta建議:在你的問題中用每個出現的「不工作」替換爲1.它在做什麼和2.你期望它做什麼。 – 2012-04-27 17:17:44