Download files from the web server by java - java

I would like to download the temp files from an web server
The code i tried is below, but i am getting only the HTML content being written the ouput file
But the url path contains 712 files in .gz format
This is the code I am using:
import java.io.*;
public class SampleFile{
public static void main(String args[]) throws IOException{
BufferedInputStream in = new BufferedInputStream(new java.net.URL("http://xxx:9080/xxx/xxx/xxx/xxx/xxx.jsp?file=/apps/WasApps/xxx/templogs/xxx.log.xxx_Server1.2012-04-01.gz").openStream());
FileOutputStream fos = new FileOutputStream("LocalPath\\koushik.txt");
BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
int x=0;
byte[] data = new byte[1024];
while((x=in.read(data,0,1024))>=0) {
bout.write(data,0,x);
}
bout.close();
in.close();
}
}

Related

Cannot open generated zip file

I've followed several articles to create a zip file using java ZipOutputStream class. The zip is created but I cannot open it. On my Mac I'm receiving this message when I open it with the unzip command :
End-of-central-directory signature not found. Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive. In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
unzip: cannot find zipfile
directory in one of /Users/xxxx/Downloads/iad.zip or
/Users/xxxx/Downloads/iad.zip.zip, and cannot find /Users/xxxx/Downloads/iad.zip.ZIP, period.
My java class :
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static java.util.Arrays.stream;
#Slf4j
#UtilityClass
public class ZipCreator {
public byte[] compressAll(String... files) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(baos)) {
stream(files)
.forEach(file -> addToZip(zipOut, file));
return baos.toByteArray();
}
}
private static void addToZip(ZipOutputStream zipOut, String file) {
File fileToZip = new File(file);
try (FileInputStream fis = new FileInputStream(fileToZip.getCanonicalFile())) {
zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
} catch (IOException e) {
log.error("Error when adding file {} to zip", file, e);
}
}
}
Doas anyone have an idea to get this zip open ?
You forgot to call closeEntry(). And you should call close() for ZipOutputStream before baos.toByteArray():
public static byte[] compressAll(String... files) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zipOut = new ZipOutputStream(baos)) {
stream(files).forEach(file -> addToZip(zipOut, file));
}
return baos.toByteArray();
}
private static void addToZip(ZipOutputStream zipOut, String file) {
File fileToZip = new File(file);
try (FileInputStream fis = new FileInputStream(fileToZip.getCanonicalFile())) {
zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
zipOut.closeEntry();
} catch (IOException e) {
log.error("Error when adding file {} to zip", file, e);
}
}
For ByteArrayOutputStream you must close ZipOutputStream before retrieve byte array from ByteArrayOutputStream.
For FileOutputStream is the same. You must close ZipOutputStream before closing FileOutputStream. Note that the close methods of resources are called in the opposite order of their creation.
public static void compressAll(String... files) throws IOException {
try (FileOutputStream fos = new FileOutputStream("test.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos)) {
stream(files).forEach(file -> addToZip(zipOut, file));
}
}

Java - FileOutputStream overwrites file, but it doesn't seem to change

So, when I write to a file using FileOutputStream, it does change the file's contents, seen as when I read it with an InputStream I get exactly what I wrote. However, when I open the file in the resources directory, it remains the same as before, despite it being changed.
My code:
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
public class Program {
public static void main(String[] args) throws URISyntaxException, IOException {
String edit = "Edit2";
String fileName = "/File.txt";
URL url = Object.class.getResource(fileName);
try (FileOutputStream fos = new FileOutputStream(new File(url.toURI()))) {
fos.write(edit.getBytes());
}
try(InputStream is = Object.class.getResourceAsStream(fileName)) {
StringBuilder sb = new StringBuilder();
int read = is.read();
while (read != -1) {
sb.append((char) read);
read = is.read();
}
System.out.println(sb.toString());
}
}
}
By the way, I am using IntelliJ IDEA, and have this file on the resources folder. It's just a .txt file with contents Not changed, so I can know if it was overwritten.
I would want to know whether this problem is related to code or not, and if it is, how can I fix it?
Sounds silly, but try refreshing the folder before opening the file.
Turns out that I shouldn't be using Object.class.getResource(fileName) to open the file from the classpath, but instead directly instantiating a File object.
import java.io.*;
public class Program {
public static void main(String[] args) throws IOException {
String edit = "Edit";
String fileName = "resources/File.txt";
File file = new File(fileName);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(edit.getBytes());
}
try (InputStream is = new FileInputStream(file)) {
StringBuilder sb = new StringBuilder();
int read = is.read();
while (read != -1) {
sb.append((char) read);
read = is.read();
}
System.out.println(sb.toString());
}
}
}
I believed it's related to the path, as CHN pointed out.

FileNotFound Exception in FileOutputStream

I'm getting error of FileNotFound. Basically, I'm trying to upload file from client to server.
Please, help me with it.
This is client.java class
package ftppackage;
import java.net.*;
import java.io.*;
public class Client {
public static void main (String [] args ) throws IOException {
Socket socket = new Socket("127.0.0.1",15123);
File transferFile = new File ("D:\\AsiaAd.wmv");
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending Files...");
os.write(bytearray,0,bytearray.length);
os.flush();
socket.close();
System.out.println("File transfer complete");
}
}
And this is my server.java class
package ftppackage;
import java.net.*;
import java.io.*;
public class Server {
public static void main (String [] args ) throws IOException {
int filesize=1022386;
int bytesRead;
int currentTot = 0;
ServerSocket serverSocket = new ServerSocket(15123);
Socket socket = serverSocket.accept();
System.out.println("Accepted connection : " + socket);
byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("E:\\0\\"); // it is creating new file not copying the one from client
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;
do {
bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0)
currentTot += bytesRead;
} while(bytesRead > -1);
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
socket.close();
}
}
Plus, guide me how do add progress bar in it with percentage. I read about SwingWorker here but unable to implement it as I'm totally new with threading concepts.
Thank you for considering my questions.
FileNotFoundException is something you will get if you point the File Object to some File which is not existing in that path. it means what ever the file you are trying to upload in not there in the specified path. SO make sure you give a valid path.

Can't write file to zip

I try to put some file fileNamePath in zip archive (arguments are D:\text.txt D:\archive.zip):
public static void main(String[] args) throws IOException {
if (args.length==0) return;
String fileNamePath = args[0];
String zipPath = args[1];
FileOutputStream outputStream = new FileOutputStream(zipPath);
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
zipOutputStream.putNextEntry(new ZipEntry(fileNamePath));
File file = new File(fileNamePath);
Files.copy(file.toPath(),zipOutputStream);
zipOutputStream.closeEntry();
zipOutputStream.close();
}
Archive is created but i don't see any file in it. Why?
That code is working perfectly:
zip.java
import java.io.*;
import java.nio.file.*;
import java.util.zip.*;
public class zip
{
public static void main(String[] args) throws IOException {
if (args.length==0) return;
String fileNamePath = args[0];
String zipPath = args[1];
FileOutputStream outputStream = new FileOutputStream(zipPath);
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
zipOutputStream.putNextEntry(new ZipEntry(fileNamePath));
File file = new File(fileNamePath);
Files.copy(file.toPath(),zipOutputStream);
zipOutputStream.closeEntry();
zipOutputStream.close();
}
}
I have compiled it under Debian 9 Stretch, OpenJDK 8
I have then created a sample txt file:
hello.txt
Hello World
I then compiled it:
javac zip.java
And finally run it:
java zip hello.txt hello.zip
I extract the .zip and open up hello.txt, returning Hello World
May it be that you have no permissions to read/write D:\?

Java stream classes : How to make a win zip Application

I want to make a win zip software. I am reading java stream classes and zip class but my mind can't work in this topic. Please help me How to do this. This my minor project in my college. I made two project in java.
Library management System
Diagnostic Lab Management
But Teacher say Management project not allowed. Please help me
This code work in one directory make for multidirectory
My Program Code
import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.util.*;
import java.io.*;
class MyZip{
FileInputStream fis;
BufferedInputStream bis;
FileOutputStream fos;
BufferedOutputStream bos;
ZipOutputStream zout;
ZipEntry ze;
public MyZip()throws IOException{
Console con=System.console();
System.out.println("How many directories do u want to compressed:");
int no_file=Integer.parseInt(con.readLine());
String inputFile[]=new String[no_file];
File fileArray[]=new File[no_file];
System.out.println("Enter the path of directories to be compressed:");
for(int i=0;i<inputFile.length;i++){
inputFile[i]=con.readLine();
fileArray[i]=new File(inputFile[i]);
}
String outputFile="E:\\MyProgram\\MyZip\\MyZip.zip";
fos=new FileOutputStream(outputFile);
bos=new BufferedOutputStream(fos);
zout=new ZipOutputStream(bos);
zipFile(fileArray);
zout.close();
bos.close();
fos.close();
getZipEntry();
}
public void getZipEntry()throws IOException{
ZipFile zf=new ZipFile("E:\\MyProgram\\MyZip\\MyZip.zip");
System.out.println(zf.getName());//return name of zip file
Enumeration e=zf.entries();
while(e.hasMoreElements()){
ZipEntry ze=(ZipEntry)e.nextElement();
System.out.print(ze.getName()+"\t");//return name of entry
System.out.print(ze.getSize()+"\t");//return uncompressed size
System.out.print(ze.getCompressedSize());//return compressed size
System.out.println();
}
zf.close();
}
public void zipFile(File farr[])throws IOException{
for(File f:farr){
if(f.isFile()){
writeFile(f);
}
if(f.isDirectory()){
File fileArray[]=f.listFiles();
zipFile(fileArray);
}
}
}
public void writeFile(File f)throws IOException{
ze=new ZipEntry(f.getPath());
zout.putNextEntry(ze);
fis=new FileInputStream(f);
bis=new BufferedInputStream(fis);
int ch;
while((ch=bis.read())!=-1)
zout.write(ch);
bis.close();
fis.close();
zout.closeEntry();
zout.flush();
}
public static void main(String args[]) throws IOException{
new MyZip();
}
}
Use for unzip your code only for zip
import java.io.*;
import java.util.*;
import java.util.zip.*;
class MyUnZip
{
FileInputStream fis;
BufferedInputStream bis;
ZipInputStream zis;
FileOutputStream fos;
BufferedOutputStream bos;
public MyUnZip(String inputFile)throws IOException{
String path1=inputFile.substring(0,inputFile.lastIndexOf('.'));
//System.out.println(path1);
fis=new FileInputStream(inputFile);
bis=new BufferedInputStream(fis);
zis=new ZipInputStream(bis);
File outputFile;
ZipEntry ze=null;
while((ze=zis.getNextEntry())!=null){
String str=ze.getName();
//System.out.println(str);
File fileName=new File(str);
String path2=str.substring(str.indexOf('\\'),str.lastIndexOf('\\'));
//System.out.println(path2);
String path3=path1+path2;
System.out.println(path3);
File filePath=new File(path3);
filePath.mkdirs();
outputFile=new File(path3,fileName.getName());
fos=new FileOutputStream(outputFile);
bos=new BufferedOutputStream(fos);
int ch;
while((ch=zis.read())!=-1)
bos.write(ch);
bos.close();
fos.close();
zis.closeEntry();
}
zis.close();
}
public static void main(String args[]) throws IOException{
Console con=System.console();
System.out.println("Enter the path of zip file to be uncompressed:");
String inputFile=con.readLine();
new MyUnZip(inputFile);
}
}

Categories

Resources