簡體   English   中英

從服務器下載文件的java代碼

[英]java code to download a file from server

在Windows中使用java代碼我需要從放在服務器中的目錄下載幾個文件。 服務器中的那些文件是單獨生成的。 所以我不知道那些文件的名稱。 有沒有辦法使用JAVA下載它並將其保存在特定的文件夾中。

我正在使用apache tomcat。

我閱讀了與java文件下載相關的所有其他線程。 但它們都不符合我的要求。

  try {
        // Get the directory and iterate them to get file by file...
        File file = new File(fileName);

        if (!file.exists()) {
            context.addMessage(new ErrorMessage("msg.file.notdownloaded"));
            context.setForwardName("failure");
        } else {
            response.setContentType("APPLICATION/DOWNLOAD");
            response.setHeader("Content-Disposition", "attachment"+ 
                                     "filename=" + file.getName());
            stream = new FileInputStream(file);
            response.setContentLength(stream.available());
            OutputStream os = response.getOutputStream();      
            os.close();
            response.flushBuffer();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

希望你有所了解......

您好,您可以使用以下代碼片段直接下載文件:

    URL oracle = new URL("http://www.example.com/file/download?");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(oracle.openStream()));

    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();

請參考[URL]中的openStream: http ://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html

您可以使用HttpURLConnection通過HTTP,HTTPS下載文件

使用java.net.URLjava.net.URLConnection類。

只有服務器列出目錄內容才有可能。 如果是,您可以發出HTTP請求:

HTTP://服務器:端口/文件夾

這會給你文件列表。

一旦你有了這個,你可以通過解析這個http請求的輸出來下載單個文件。

如果它是服務器,則該過程必須類似於使用您必須加載文件的FTP憑據。 這個java文件下載示例可能對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM