How to initiate a file download in the browser using Java? - java

I am creating a simple application thats uploads and downloads files to/from a server.
For testing purposes I am using localhost for testing. I am looking for a simple way to download a file from the browser in Java.

Here is a code to download files from a web site in Java ... You can adapt this
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class DownloadFile {
public static void main(String[] args) throws IOException {
String fileName = "fileName.txt";
URL link = new URL("http://websiteToDownloadFrom.com");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
}
}
If it is in localhost:
url = new URL("http://localhost:8052/directoryPath/fileName.pdf");

Related

How can i copy png files? and Dynamic directory path

So I wrote this code that copies a file from a folder to another one!
it works fine with .mp3 .wav .jpeg.jpg files
but it doesn't work properly with .png files!
(the image is destroyed or half of it is missed)
Is there a way I can edit the code is it works with .png files?
if no, how can I copy them?
I also want to add another question! the current code works on my computer
because of this path D:\\move\\1\\1.mp3 exist on my computer!
if I convert my program to .exe file and give it to someone else it doesn't work because that path doesn't exist on his computer!
so instead of this line
FileInputStream up = new FileInputStream("D:\\move\\1\\images\\1.jpg");
i wanna make something like
FileInputStream up = new FileInputStream(findAppFolder+"\\images\\1.jpg");
code :
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileInputStream up = new FileInputStream("D:\\move\\1\\images\\1.jpg");
FileOutputStream down = new FileOutputStream("D:\\move\\2\\images\\2.jpg");
BufferedInputStream ctrl_c = new BufferedInputStream(up);
BufferedOutputStream ctrl_v = new BufferedOutputStream(down);
int b=0;
while(b!=-1){
b=ctrl_c.read();
ctrl_v.write(b);
}
ctrl_c.close();
ctrl_v.close();
}
}
Try this way:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Path source=Paths.get("abc.png");
Path destination=Paths.get("abcNew.png");
Files.copy(source, destination);
Or if you want to use with Java input/output try this way:
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer all byte from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}

Java code downloading data from this url

So I am new to java programming and I am supposed to download data from the URL below every 5 minute.
host: 204.8.38.210
Get:/Iowa.Sims.AllSites.C2C/IADOT_SIMS_AllSites_C2C.asmx/OP_ShareTrafficDetectorData?MSG_TrafficDetectorDataRequest=string%20HTTP/1.1
I get this error-"Server returned HTTP response code : 400 " using this code below
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class JavaDownload {
public static void main(String[] args) throws IOException{
String fileName = "file3x.html";
URL link = new URL("http://204.8.38.210/Iowa.Sims.AllSites.C2C/IADOT_SIMS_AllSites_C2C.asmx/OP_ShareTrafficDetectorData?MSG_TrafficDetectorDataRequest=string%20HTTP/1.1");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n=0;
while(-1!=(n=in.read(buf)))
{
out.write(buf,0,n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
System.out.println("Finished");
}
}

FileOutputStream zip file open ERROR: "File cannot be opened as an archive"

I am trying to create ".zip" file from byte array but the error given appear everytime I am attempt to open it. Here is the code:
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.PrintWriter;
public class ReadTxtFile {
public static void BinFileContToBinArr(String path) throws Throwable{
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try{
String el = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
inputStream = new BufferedReader(new FileReader(path));
FileOutputStream fos = new FileOutputStream("D:/texttNE22W.zip");
while((el=inputStream.readLine()) != null){
baos.write(el.getBytes());
}
byte[] b = baos.toByteArray();
for(int i = 0; i<b.length; i++){
System.out.print((char)b[i] + " ");
}
fos.write(b);
}
finally{
if (inputStream!=null){
inputStream.close();
}
if(outputStream!=null){
outputStream.close();
}
}
}
public static void main(String[] args) throws Throwable {
String path = "D:/text.txt";
BinFileContToBinArr(path);
}
}
I've made a research but didn't find a solution. Also, I tried to create a ".txt" file and it works. The only problem is when it comes to creating a ".zip".
Thank you beforehand ! By the way, if someone have encountered this problem before, feel free to vote up or leave me a comment if you wish, because I am interested if it is a common mistake.
You need to use ZipOutputStream instead of FileOutputStream.

When trying to zip up and compress multiple files, how do you zip using InputStream and return as InputStream?

I have an excel file that I want to send as an attachment in email as well as a couple other text files, but I want to zip those files for size reasons. How would I go about this using InputStream and returning as InputStream? Any help is much appreciated.
You can use the below code to create Zip File.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFileTest
{
public static void main( String[] args )
{
byte[] buffer = new byte[1024];
try{
FileOutputStream fos = new FileOutputStream("C:\\MyFile.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze= new ZipEntry("spy.log");
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream("C:\\spy.log");
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
//remember close it
zos.close();
System.out.println("Done");
}catch(IOException ex){
ex.printStackTrace();
}
}
}

Reading video data and writing to another file java

I am reading a video file data in bytes and sending to another file but the received video file is not playing properly and is chattered.
Can anyone explain me why this is happening and a solution is appreciated.
My code is as follows
import java.io.*;
public class convert {
public static void main(String[] args) {
//create file object
File file = new File("B:/music/Billa.mp4");
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(file);
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
//create string from byte array
String strFileContent = new String(fileContent);
System.out.println("File content : ");
System.out.println(strFileContent);
File dest=new File("B://music//a.mp4");
BufferedWriter bw=new BufferedWriter(new FileWriter(dest));
bw.write(strFileContent+"\n");
bw.flush();
}
catch(FileNotFoundException e)
{
System.out.println("File not found" + e);
}
catch(IOException ioe)
{
System.out.println("Exception while reading the file " + ioe);
}
}
}
This question might be dead but someone might find this useful.
You can't handle video as string. This is the correct way to read and write (copy) any file using Java 7 or higher.
Please note that size of buffer is processor-dependent and usually should be a power of 2. See this answer for more details.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileCopy {
public static void main(String args[]) {
final int BUFFERSIZE = 4 * 1024;
String sourceFilePath = "D:\\MyFolder\\MyVideo.avi";
String outputFilePath = "D:\\OtherFolder\\MyVideo.avi";
try(
FileInputStream fin = new FileInputStream(new File(sourceFilePath));
FileOutputStream fout = new FileOutputStream(new File(outputFilePath));
){
byte[] buffer = new byte[BUFFERSIZE];
while(fin.available() != 0) {
bytesRead = fin.read(buffer);
fout.write(buffer, 0, bytesRead);
}
}
catch(Exception e) {
System.out.println("Something went wrong! Reason: " + e.getMessage());
}
}
}
Hope this also helpful for you - This can read and write a file into another file (You can use any file type to do that)
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Copy {
public static void main(String[] args) throws Exception {
FileInputStream input = new FileInputStream("input.mp4"); //input file
byte[] data = input.readAllBytes();
FileOutputStream output = new FileOutputStream("output.mp4"); //output file
output.write(data);
output.close();
}
}
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import javax.imageio.ImageIO;
public class Reader {
public Reader() throws Exception{
File file = new File("C:/Users/Digilog/Downloads/Test.mp4");
FileInputStream fin = new FileInputStream(file);
byte b[] = new byte[(int)file.length()];
fin.read(b);
File nf = new File("D:/K.mp4");
FileOutputStream fw = new FileOutputStream(nf);
fw.write(b);
fw.flush();
fw.close();
}
}
In addition to Jakub Orsula's answer, one needs to check the result of read operation to prevent garbage being written to end of file in last iteration.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileCopy {
public static void main(String args[]) {
final int BUFFERSIZE = 4 * 1024;
String sourceFilePath = "D:\\MyFolder\\MyVideo.avi";
String outputFilePath = "D:\\OtherFolder\\MyVideo.avi";
try(
FileInputStream fin = new FileInputStream(new File(sourceFilePath));
FileOutputStream fout = new FileOutputStream(new File(outputFilePath));
){
byte[] buffer = new byte[BUFFERSIZE];
int bytesRead;
while(fin.available() != 0) {
bytesRead = fin.read(buffer);
fout.write(buffer, 0, bytesRead);
}
}
catch(Exception e) {
System.out.println("Something went wrong! Reason: " + e.getMessage());
}
}
}

Categories