This question already has answers here:
Download file from server in java
(2 answers)
Closed 4 years ago.
guys!
I have a problem! I'm trying to download a .zip (size is 150 mb) file from Internet using this code:
public void downloadBuild(String srcURL, String destPath, int bufferSize, JTextArea debugConsole) throws FileNotFoundException, IOException {
debugConsole.append(String.format("**********Start process downloading file. URL: %s**********\n", srcURL));
try {
URL url = new URL(srcURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.connect();
in = httpConn.getInputStream();
out = new FileOutputStream(destPath);
byte buffer[] = new byte[bufferSize];
int c = 0;
while ((c = in.read(buffer)) > 0) {
out.write(buffer, 0, c);
}
out.flush();
debugConsole.append(String.format("**********File. has been dowloaded: Save path is: %s********** \n", destPath));
} catch (IOException e) {
debugConsole.append(String.format("**********Error! File was not downloaded. Detail: %s********** \n", e.toString()));
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
}
but the file is not completely downloaded. (only 4000 bytes). What am I doing wrong?
you can use the following code to download and extract zip file from given uri path.
URL url = new URL(uriPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
ZipInputStream zipIn = new ZipInputStream(in);
ZipEntry entry = zipIn.getNextEntry();
while(entry != null) {
System.out.println(entry.getName());
if (!entry.isDirectory()) {
// if the entry is a file, extracts it
System.out.println("===File===");
} else {
System.out.println("===Directory===");
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
FileOutputStream("example.zip").getChannel().transferFrom(Channels.newChannel(new URL("http://www.example.com/example.zip").openStream()), 0, Long.MAX_VALUE);
Simple one-liner. For more info, read here
Related
Hi I was trying to read a PDF file online but after reading and writing on local. after viewing the document I am getting an error that content is not supported .
URL url1 =
new URL("http://www.gnostice.com/downloads/Gnostice_PathQuest.pdf");
byte[] ba1 = new byte[1024];
int baLength;
FileOutputStream fos1 = new FileOutputStream("/mnt/linuxabc/research_paper/Gnostice_PathQuest.pdf");
try {
URLConnection urlConn = url1.openConnection();
/* if (!urlConn.getContentType().equalsIgnoreCase("application/pdf")) {
System.out.println("FAILED.\n[Sorry. This is not a PDF.]");
} else {*/
try {
InputStream is1 = url1.openStream();
while ((baLength = is1.read(ba1)) != -1) {
fos1.write(ba1, 0, baLength);
}
fos1.flush();
fos1.close();
is1.close();
} catch (ConnectException ce) {
System.out.println("FAILED.\n[" + ce.getMessage() + "]\n");
}
// }
Your Pdf Link actually redirects to https://www.gnostice.com/downloads.asp, so there is no pdf directly behind the link.
Try with another link: check first in a browser of your choice that invoking the pdf's url render a real pdf in the browser.
The code below is practically the same as yours except for the pdf's url and the output's path, and I am also adding exception throws to the main method's signature and simply printing the content type.
It works as expected:
public class PdfFileReader {
public static void main(String[] args) throws IOException {
URL pdfUrl = new URL("http://www.crdp-strasbourg.fr/je_lis_libre/livres/Anonyme_LesMilleEtUneNuits1.pdf");
byte[] ba1 = new byte[1024];
int baLength;
try (FileOutputStream fos1 = new FileOutputStream("c:\\mybook.pdf")) {
URLConnection urlConn = pdfUrl.openConnection();
System.out.println("The content type is: " + urlConn.getContentType());
try {
InputStream is1 = pdfUrl.openStream();
while ((baLength = is1.read(ba1)) != -1) {
fos1.write(ba1, 0, baLength);
}
fos1.flush();
fos1.close();
is1.close();
} catch (ConnectException ce) {
System.out.println("FAILED.\n[" + ce.getMessage() + "]\n");
}
}
}
}
Output:
The content type is: application/pdf
private static String readPdf() throws MalformedURLException, IOException {
URL url = new URL("https://colaboracion.dnp.gov.co/CDT/Sinergia/Documentos/Informe%20al%20Congreso%20Presidencia%202017_Baja_f.pdf");
BufferedReader read = new BufferedReader(
new InputStreamReader(url.openStream()));
String i;
StringBuilder stringBuilder = new StringBuilder();
while ((i = read.readLine()) != null) {
stringBuilder.append(i);
}
read.close();
return stringBuilder.toString();
}
I'm struggling against the uncompleted download of a file.
For example, I upload some data on github :https://gist.githubusercontent.com/rdanniau/3b7f26bb1101b28400bf24f2f9664828/raw/980d6ff511404bf14d3efc56be3dfb081541991f/LEDirium.hex
and on pasteBin : http://pastebin.com/raw/FcVfLf5b
I want to retrieve them and save them into a file "filename".
I've watch a lot of example on internet and it must be working.
Here is the code :
private void download(final URL myUrl){
new Thread(new Runnable() {
//InputStream is = null;
//FileOutputStream fos = null;
public void run() {
try {
URLConnection connection = myURLL.openConnection();
//HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
//connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(10000);
connection.connect();
//is = myUrl.openStream();
is = connection.getInputStream();
File file = new File(context.getFilesDir(),fileName);
file.delete();
file = new File(context.getFilesDir(),fileName);
fos = new FileOutputStream(file);
byte data[] = new byte[1024];
String str ="";
int count = 0;
while ((count = is.read(data)) != -1) {
fos.write(data, 0, count);
}
is.close();
fos.close();
}
catch (Exception e) {
downloadedFileCallback.onError(e);
Log.e("DownloadedFile", "Unable to download : " + e.getMessage() + " cause :" + e.getCause());
return;
}
downloadedFileCallback.onDownloadedFinished();
readFile(context);
}
}).start();
}
public void readFile(Context context){
// read
try {
BufferedReader br = new BufferedReader(new FileReader(new File(context.getFilesDir(),fileName)));
String line;
while ((line = br.readLine()) != null) {
Log.v("DL", line);
}
br.close();
}
catch (Exception e) {
Log.e("DownloadedFile", "Unable to read : " + e.getMessage() + " cause :" + e.getCause());
}
//Log.v("DownloadedFile", text.toString());
}
where myURL are called like
URL myURL = new URL("http://pastebin.com/raw/FcVfLf5b");
In the Log.v, I can see that I downloaded only a part of the file which is never the same (it could be the entire file, the half, the quarter, we don' know...)
It's probably the inputStream connection which is closed too fast. But why ?
Last question, instead of using Log.v to check if the file is correctly downloaded. Where can I found it on my phone ? I searched in many folders but I never seen my File.
Thanks a lot for any advice
EDIT : It seems to be the same here InputStream returns -1 before end of file but no one answered.
I am currently working on an application and I wrote it with Java. It is downloading some media files to local computer and open it with a Java method called Desktop.getDesktop().open(file); It is working good on windows but it is not working on debian.
Here is used download from url method:
public String DownloadFromUrlAndGetPath(String DownloadUrl) {
String fileName="";
try {
URL url = new URL(DownloadUrl);
URLConnection ucon = url.openConnection();
String raw = ucon.getHeaderField("Content-Disposition");
// raw = "attachment; filename=abc.mp3"
if(raw != null && raw.indexOf("=") != -1) {
fileName = raw.split("=")[1]; //getting value after '='
fileName = fileName.replace("\"", "").trim();
} else {
return "";
}
File file = new File(Paths.get(System.getProperty("user.home"), "MyFolderToSaveFiles") +"/"+ fileName);
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
try {
baf.append((int)((byte)current));
continue;
}
catch (Exception var12_13) {
}
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
}
catch (IOException e) {
e.getMessage();
}
}
return Paths.get(System.getProperty("user.home"), "MyFolderToSaveFiles") +"/"+ fileName;
Then I want to open that file like that:
File f = new File(url);
Desktop.getDesktop().open(f);
And the error says;
Any suggestion ? Thanks
I solved that with using this , so when I open file I am using xdg-open..
I want to download a file from a Server into a client machine. But i want the file to be downloaded from a browser : I want the file to be saved at the Downloads Folder.
Im using the following code to download files.
public void descarga(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
// Get the URL
URL url = new URL(address);
// Open an output stream to the destination file on our local filesystem
out = new BufferedOutputStream(new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
// Get the data
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
// Done! Just clean up and get out
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
// Shouldn't happen, maybe add some logging here if you are not
// fooling around ;)
}
}
It works but unless i specify the absolute path it does not download the file, therefore is useless to use from different clients with different browsers, because the webpage does not even prompts the message that lets the user know that a file is being downloaded. What can i add to get that to work?
Thanks
I am trying to Post a .txt file to a local tomcat webserver that i have on my system.
But when i try to do a post then i get a Error: Not Found.
The source file is present but even after that i get this error.
Can you please let me know what i am doing wrong here. i have pasted my code below.
File file = new File("C:\\xyz\\test.txt");
URL url = new URL("http://localhost:8080/process/files");
urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
urlconnection.setRequestMethod("POST");
BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int i; // read byte by byte until end of stream
while ((i = bis.read()) >0) {
bos.write(i);
}
bos.close();
System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());
} catch(Exception ae)
{
ae.printStackTrace();
}
try {
InputStream inputStream;
int responseCode=((HttpURLConnection)urlconnection).getResponseCode();
if ((responseCode>= 200) &&(responseCode<=202) ) {
inputStream = ((HttpURLConnection)urlconnection).getInputStream();
int j;
while ((j = inputStream.read()) >0) {
System.out.println("------ TESTING ------");
}
} else {
inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
}
((HttpURLConnection)urlconnection).disconnect();
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
}
Can you please let me know what is going wrong here.
I am scratching my head on this for a long time now.
Thanks
Vikeng
The URL you are POSTing to needs to point to a servlet or something similar. You cannot upload a file to a directory just by sending a POST request--the POST request has to be handled by something.