我想使用下面的代碼按鈕單擊下載文件並將其保存到一個位置。但是,它始終返回目標目標找不到。它似乎不創建所需的目錄。我必須告訴它這樣做嗎?還是應該爲我做?下面是我使用的功能:Java下載到目標(目標無法找到)和0字節文件下載
public void actionPerformed(ActionEvent ae) {
try {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(filelocation.getText());
String URL_LOCATION = "http://www.futureretrogaming.tk/gamefiles/ProfessorPhys.iso";
String LOCAL_FILE = (filelocation.getText() + "\\ProfessorPhys\\");
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.out.println(e);
}
編輯:
如果我手動創建它下載(有點)的目錄。無論如何要檢查目錄是否已經存在,以及它是否不創建它?而且,當它下載時,它只是使文件不會下載,因爲下載的文件顯示爲0字節。我怎樣才能解決這個問題?
編輯:
我已經創建了下面的代碼來檢查,如果該目錄存在,如果它不,創建它。然而,這確實起作用,唯一仍然不起作用的是下載。我現在已經在題目中列入了這個問題。
,誰想要的作品它的代碼如下:
String LOCAL_FILE = (filelocation.getText() + "\\ProfessorPhys\\");
File localfile = new File(LOCAL_FILE);
if (localfile.exists()) {
System.out.println("Directory exists!");
}
else {
System.out.println("Directory doesn't exist! Creating...");
localfile.mkdir();
if (localfile.exists())
System.out.println("Directory created!");
}
是你身後的代理? –
也會打開URL,但實際上是0字節長。你確定這是正確的網址嗎?你有沒有嘗試過使用不同的(如google.de或其他文件,你_KNOW_存在) –
其我的文件在我的服務器上,所以我不明白爲什麼它不會工作,但我會仔細檢查URL。我也編輯了一下我的問題。 – Kyle