Downloader code in java

How to make a java fiel downloader

This method is to search for specific file with partial or full text in download folder for given time and returns the absolute path of the file. Solution 2: If you use the idea to write content to HttpServletResponse’s output stream while offering download service, rather than saving the content locally and then reading the file as FileInputStream, you can just convert the file content to InputStream by .

How to make a downloader in java

You need to write the amount that was read.

When you read into the buffer you can read fewer than 1024 bytes. For example a 1200-byte file would be read as 1024 + 176. Your count variable stores how much was actually read, which would be 176 the second time around your loop.

The reason for corruption is that you would be writing 176 ‘good’ bytes plus (1024 — 176 = 848) additional bytes that were still in the data array from the previous read.

while( ((count=bufferedInputStream.read(data,0,1024))!=-1) )

The zero offset in that write call is an offset into data , which you really do want to be zero. See the Javadoc for details. There is no difference for other stream types.

Читайте также:  Json with php and ajax

How to wait till file is getting downloaded or available in required, Create a method to check whether a file is fully downloaded or not. Call that method wherever it’s required. Method to check file is

Java Tutorial — How to download file from a URL

JAVA- Download a file from URL

Java Example to Download File Using HttpURLConnection

This Java video tutorial demonstrates how to write a Java program to download files from
Duration: 13:31

Create a text file for download on the fly with Java

Any text that you generate in the Servlet can simply be written to the OutputStream returned by ServletResponse.getOutputStream() .

If you want the output to be downloadable as a file, you can follow the approach in this answer — https://stackoverflow.com/a/11772700/1372207

The difference would be, that the Content-type would be text/plain and instead of reading from another inputstream, you would just write the String objects directly to the ServletOutputStream using the print(String) method.

If you use the idea to write content to HttpServletResponse’s output stream while offering download service, rather than saving the content locally and then reading the file as FileInputStream, you can just convert the file content to InputStream by InputStream stream = new ByteArrayInputStream(exampleString.getBytes(«UTF-8»)); .

The following code partially references https://www.codejava.net/java-ee/servlet/java-servlet-download-file-example.

 public void doDownload(HttpServletRequest request, HttpServletResponse response) throws IOException < String fileName = "xxx.txt"; String fileContent = ""; // get absolute path of the application ServletContext context = request.getServletContext(); // get MIME type of the file String mimeType = context.getMimeType(fileName); if (mimeType == null) < // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; >setResponseHeader(response, fileName, mimeType, (int) fileContent.length()); InputStream inputStream = new ByteArrayInputStream(fileContent.getBytes("UTF-8")); // get output stream of the response OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; // write bytes read from the input stream into the output stream while ((bytesRead = inputStream.read(buffer)) != -1) < outStream.write(buffer, 0, bytesRead); >inputStream.close(); outStream.close(); > private void setResponseHeader(HttpServletResponse response, String fileName, String mimeType, Integer fileLength) < response.setContentType(mimeType); response.setContentLength(fileLength); response.setContentType("application/octet-stream; charset=UTF-8"); String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", fileName); response.setHeader(headerKey, headerValue); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); >

How to download a file from a url in java Code Example, InputStream in = new URL(FILE_URL).openStream();Files.copy(in, Paths.get(FILE_NAME), StandardCopyOption.REPLACE_EXISTING);

How to download a file using a java program file that is uploaded in a website

For Downloading a file Create a function like this as follows:

private void exportExcel(HttpServletResponse response, HSSFWorkbook workbook) throws CpaServiceException< try< response.reset(); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + workbook.getSheetAt(0).getSheetName()+".xls"); workbook.write(response.getOutputStream()); >catch(IOException e) < throw new CpaServiceException(CpaConstants.APPLICATION_GENERAL_ERROR); >> 

Then Call the function as:

@RequestMapping(value = "/"+ControllerPaths.GET_EXCEL_FOR_COMMON_PROCESS_SYSTEM_REPORT, method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public void getExcelForCommonProcessSystemReport(HttpServletRequest request, HttpServletResponse response, CpaReportFilterDTO filterDTO) throws Exception

The above code is a sample one. You can do it the similar way to download a document form the browser.

Create a text file for download on the fly with Java, If you use the idea to write content to HttpServletResponse’s output stream while offering download service, rather than saving the content

How to wait till file is getting downloaded or available in required folder?

  • Create a method to check whether a file is fully downloaded or not.
  • Call that method wherever it’s required.

Method to check file is downloaded or not : This method is to search for specific file with partial or full text in download folder for given time and returns the absolute path of the file.

@param fileText - Partial or full file name @param fileExtension - .pdf, .txt @param timeOut - How many seconds you are expecting for file to be downloaded. 
 public static String isFileDownloaded(String fileText, String fileExtension, int timeOut) < String folderName = "location of download folde"; File[] listOfFiles; int waitTillSeconds = timeOut; boolean fileDownloaded = false; String filePath = null; long waitTillTime = Instant.now().getEpochSecond() + waitTillSeconds; while (Instant.now().getEpochSecond() < waitTillTime) < listOfFiles = new File(folderName).listFiles(); for (File file : listOfFiles) < String fileName = file.getName().toLowerCase(); if (fileName.contains(fileText.toLowerCase()) && fileName.contains(fileExtension.toLowerCase())) < fileDownloaded = true; filePath = file.getAbsolutePath(); break; >> if (fileDownloaded) < break; >> return filePath; > 

Call the isFileDownloaded method :

As you know the partial file name then you can pass the input like below to get the file path.

String filePath = isFileDownloaded("Personal Data", ".pdf", 30); System.out.println("Complete path of file:"+ filePath); 
C:\Users\Download\Personal data. pdf 

Updated code for OP’s logic :

Read pdf content method :

public static String readPdfContent(String fileName) throws IOException

Well you can simply list all files in folder and take the newest

File f = new File("download_folder"); String[] pathnames = f.list(); 

then you can use for-loop to find what you need

Download a File From an URL in Java, 6 days ago · The most basic API we can use to download a file is Java IO. We can use the URL class to open a connection to the file we want to download.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A java library to download files and process the download speed,progress and other things

MrMarnic/JavaDownloadLibrary

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A java library to download files and process the download speed,progress and other things

  • Download files easy
  • Check download speed
  • Check download progress
  • Directly cast download objects
  • Download Text
  • Convert file sizes (MB;GB;KB. )
Downloader downloader = new Downloader(false); downloader.downloadFileToLocation("https://github.com/MrMarnic/JIconExtract/releases/download/1.0/JIconExtract.jar","C:\\Downloads\\download.zip"); 

Add Handler (Check Speed,progress. ):

Downloader downloader = new Downloader(false); downloader.setDownloadHandler(new CombinedSpeedProgressDownloadHandler(downloader) < @Override public void onDownloadSpeedProgress(int downloaded, int maxDownload, int percent, int bytesPerSec) < System.out.println(SizeUtil.toMBFB(bytesPerSec)+"/s " + percent + "%"); >@Override public void onDownloadFinish() < super.onDownloadFinish(); System.out.println("Download finished"); >>); downloader.downloadFileToLocation("https://github.com/MrMarnic/JIconExtract/releases/download/1.0/JIconExtract.jar","C:\\Downloads\\download.zi"); 
  • DownloadSpeedDownloadHandler (check speed)
  • DownloadProgressDownloadHandler (check progress)
  • CombinedSpeedProgressDownloadHandler (check speed and progress)
public class ExampleDownloadHandler extends DownloadHandler < public DownloadProgressDownloadHandler(Downloader downloader) < super(downloader); >@Override public void onDownloadStart() < >@Override public void onDownloadFinish() < timer.cancel(); >@Override public void onDownloadError() < timer.cancel(); >> 

Syntax: SizeUtil.toMBFB() = toMegaBytesFromBytes SizeUtil.toGBFB() = toGigiaBytesFromBytes

double mb = SizeUtil.toMBFB(2000000000); double kb = SizeUtil.toKBFB(1000000); 

About

A java library to download files and process the download speed,progress and other things

Источник

Java download file

Often it is required to download a file directly from a URL and save to a directory on local system such as downloading a file from a remote repository. This requires reading a file from url and writing it to a local file.
This article will share different methods to download a file from URL in java. Methods defined here are applicable to all types of file such as a pdf file, an exe file, a txt file or a zip file etc.

  1. Create a connection to the given file url.
  2. Get input stream from the connection. This stream can be used to read file contents.
  3. Create an output stream to the file to be downloaded.
  4. Read the contents from the input stream and write to the output stream.

Java code to download file from URL with this method is given below.

import java.net.URL; import java.net.URLConnection; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileDownloader < public static void main(String[] args) < OutputStream os = null; InputStream is = null; String fileUrl = "http://200.34.21.23:8080/app/file.txt"; String outputPath = "E:\\downloads\\downloaded.txt"; try < // create a url object URL url = new URL(fileUrl); // connection to the file URLConnection connection = url.openConnection(); // get input stream to the file is = connection.getInputStream(); // get output stream to download file os = new FileOutputStream(outputPath); final byte[] b = new byte[2048]; int length; // read from input stream and write to output stream while ((length = is.read(b)) != -1) < os.write(b, 0, length); >> catch (IOException e) < e.printStackTrace(); >finally < // close streams if (os != null) os.close(); if (is != null) is.close(); >> >

Remember that the output and input paths should end with the file name else there will be an error.

All the methods in this post read a file at a remote URL. If you want to read a file at local system, then refer this post.

  1. Create an input stream to the file to be downloaded.
  2. Create a new channel that will read data from this input stream.
  3. Create an output stream that will write file contents after reading it from the channel created in Step 2.
  4. Get the channel from this output stream and write the contents from channel created in Step 2.

You will understand the algorithm better after looking at the below code example.

import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.io.File; public class FileDownloader < public static void main(String[] args) < try < String fileUrl = "http://200.34.21.23:8080/app/file.pdf"; String outputPath = "E:\\downloads\\downloaded.pdf"; URL url = new URL(fileUrl); // create an input stream to the file InputStream inputStream = url.openStream(); // create a channel with this input stream ReadableByteChannel channel = Channels.newChannel( url.openStream()); // create an output stream FileOutputStream fos = new FileOutputStream( new File(outputPath)); // get output channel, read from input channel and write to it fos.getChannel().transferFrom(channel, 0, Long.MAX_VALUE); // close resources fos.close(); channel.close(); >catch(IOException e) < e.printStackTrace(); >> >

Note that transferFrom() method of a channel takes 3 arguments.
1. input file channel,
2. position at which it will start reading the file, 0 here means the beginning of file, and
3. number of bytes that will be transferred at one time. This value is set to a very large value( Long.MAX_VALUE ) for higher efficiency.

Learn different methods of writing to a file here .

Method 3 : Using Apache Commons IO Library
Apache Commons IO Library has a org.apache.commons.io.FileUtils class which contains a method copyURLToFile() .

This method takes two arguments:
1. java.net.URL object pointing to the source file, and
2. java.io.File object which points to an output file path.

Remember that both paths should contain the name of file at the end and output path should be a location on local system at which the file will be downloaded.
copyURLToFile() reads the file from remote location and copies it to the local machine. Example,

import org.apache.commons.io.FileUtils; public class FileDownloader < public static void main(String[] args) < String fileUrl = "http://200.34.21.23:8080/app/file.zip"; String outputPath = "E:\\downloads\\downloaded.zip"; FileUtils.copyURLToFile(new URL(fileUrl), new File(outputPath)); >>

You can add Apache Commons IO dependency to your project as per the build tool.

// Gradle
compile group: ‘org.apache.commons’, name: ‘commons-io’, version: ‘1.3.2’

Hope the article was useful in explaining different ways to download a file from URL in java.
Do not forget to click the clap below.

Источник

Оцените статью