サーバーからPDFファイルをダウンロードするプログラムを作成しています。私はここでDownload file by passing URL using java code与えられたいくつかのプログラムを使用しています、このソリューションは、最初の答えで提供されたサンプルURLのためにうまく動作しますが、PDFではなく、URLだけを置き換えます。以下は私のコードです。ここでjavaを使用してpdfをダウンロードする
import java.io.*;
import java.net.*;
public class FileDownloadTest {
final static int size = 1024;
public static void fileUrl(String fAddress, String localFileName, String destinationDir) {
// localFileName = "Hello World";
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
try {
URL url;
byte[] buf;
int byteRead, byteWritten = 0;
url = new URL(fAddress);
outStream = new BufferedOutputStream(new FileOutputStream(destinationDir + "\\" + localFileName));
uCon = url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((byteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, byteRead);
byteWritten += byteRead;
}
System.out.println("Downloaded Successfully.");
System.out.println("File name:\"" + localFileName + "\"\nNo ofbytes :" + byteWritten);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void fileDownload(String fAddress, String destinationDir) {
int slashIndex = fAddress.lastIndexOf('/');
int periodIndex = fAddress.lastIndexOf('.');
String fileName = fAddress.substring(slashIndex + 1);
if (periodIndex >= 1 && slashIndex >= 0 && slashIndex < fAddress.length() - 1) {
fileUrl(fAddress, fileName, destinationDir);
} else {
System.err.println("path or file name.");
}
}
public static void main(String[] args) {
String fAddress = "http://singztechmusings.files.wordpress.com/2011/09/maven_eclipse_and_osgi_working_together.pdf";
String destinationDir = "D:\\FileDownload";
fileDownload(fAddress, destinationDir);
}
}
、このPDFファイルは、73ページを持っており、私のフォルダに、それは、ファイルが壊れている可能性がありますことを言っては、Acrobat Readerで開くと、1キロバイトのPDFとしてダウンロードしています。
ここで提供されたコードを試しましたがhttps://dzone.com/articles/java-how-save-download-fileですが、結果は同じです。
どうすればいいのか教えてください。
ありがとうございました
Hi Mandis Wohooooooooo。これはすごくうまくいった。もし私が 'http'サイトに' s'を付け加えれば、それはうまくいくのでしょうか? – user3872094
いいえ。サイトはhttpsプロトコルをサポートしている必要があります。また、httpとhttpsを使用する場合は、コンテンツが異なる可能性があります。より良い解決策は、[http-commons](https://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fundamentals.html#d5e334)のように自動的にリダイレクトを処理するhttpクライアントを使用することです。 。 –