I have a basic java program that downloads the file from a link.
I need to make it execute the file in mentioned directory.
I need it to ensure that the file has downloaded.
4.It would be nice if someone could help me.
5.Thanks for anyone willing to help me out.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class URLReader {
public static void copyURLToFile(URL url, File file) {
try {
InputStream input = url.openStream();
if (file.exists()) {
if (file.isDirectory())
throw new IOException("File '" + file + "' is a directory");
if (!file.canWrite())
throw new IOException("File '" + file + "' cannot be written");
} else {
File parent = file.getParentFile();
if ((parent != null) && (!parent.exists()) && (!parent.mkdirs())) {
throw new IOException("File '" + file + "' could not be created");
}
}
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
input.close();
output.close();
System.out.println("File '" + file + "' downloaded successfully!");
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
String sUrl = "http://localhost:8000/TestFile/file.exe";
URL url = new URL(sUrl);
File file = new File("C:/Temp/file.exe");
URLReader.copyURLToFile(url, file);
}
}
Related
Is there a way to unzip a ZIP file with various subfolders in Java without needing to install any additional plugin.
For example, I would like to unzip the file https://services.gradle.org/distributions/gradle-6.4.1-bin.zip with this code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class unzipfile {
private static void unzip(String zipFilePath, String zipFileName, String destDir) {
System.out.print("Extracting " + zipFileName + "...");
File dir = new File(destDir);
// create output directory if it doesn't exist
if(!dir.exists()) dir.mkdirs();
FileInputStream fis;
//buffer for read and write data to file
byte[] buffer = new byte[1024];
try {
fis = new FileInputStream(zipFilePath);
try (ZipInputStream zis = new ZipInputStream(fis)) {
ZipEntry ze = zis.getNextEntry();
while(ze != null){
String fileName = ze.getName();
File newFile = new File(destDir + File.separator + fileName);
//create directories for sub directories in zip
new File(newFile.getParent()).mkdirs();
try (FileOutputStream fos = new FileOutputStream(newFile)) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
//close this ZipEntry
ze = zis.getNextEntry();
}
}
fis.close();
System.out.println(" Done!");
} catch (IOException e) {
System.out.println(" Error while extracting " + zipFileName);
Logger.getLogger(unzipfile.class.getName()).log(Level.SEVERE, null, e);
}
}
public static void main(String[] args) {
try{
unzip(args[0], args[1], args[2]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No valid arguments specified. Usage:\n");
System.out.println("\'java unzipfile [ZIP file path with file name] [file name only] [target directory]\'");
System.exit(1);
}
}
}
I run:
java unzipfile path\to\file\gradle-6.4.1-bin.zip gradle-6.4.1-bin.zip .
But when I run the full application it gives me the message:
Extracting gradle-6.4.1-bin.zip... Error while extracting gradle-6.4.1-bin.zip
may. 27, 2020 5:44:37 P.áM. unzipfile unzip
SEVERE: null
java.io.FileNotFoundException: .\gradle-6.4.1\README (El sistema no puede encontrar la ruta especificada)
at java.base/java.io.FileOutputStream.open0(Native Method)
at java.base/java.io.FileOutputStream.open(FileOutputStream.java:291)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:234)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:184)
at unzipfile.unzip(unzipfile.java:29)
at unzipfile.main(unzipfile.java:50)
Thanks for your time.
Finally, I've found this working code:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class unzipfile {
public static void main(String[] args) {
String filename = args[0];
File srcFile = new File(filename);
// create a directory with the same name to which the contents will be extracted
String zipPath = filename.substring(0, filename.length()-4);
File temp = new File(zipPath);
temp.mkdir();
ZipFile zipFile = null;
try {
zipFile = new ZipFile(srcFile);
// get an enumeration of the ZIP file entries
Enumeration e = zipFile.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
File destinationPath = new File(zipPath, entry.getName());
//create parent directories
destinationPath.getParentFile().mkdirs();
// if the entry is a file extract it
if (!entry.isDirectory())
System.out.println("Extracting file: " + destinationPath);
try (BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry))) {
int b;
byte buffer[] = new byte[1024];
FileOutputStream fos = new FileOutputStream(destinationPath);
try (BufferedOutputStream bos = new BufferedOutputStream(fos, 1024)) {
while ((b = bis.read(buffer, 0, 1024)) != -1) {
bos.write(buffer, 0, b);
}
}
}
}
}
catch (IOException ioe) {
System.out.println("Error opening zip file" + ioe);
}
finally {
try {
if (zipFile!=null) {
zipFile.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing zip file" + ioe);
}
}
}
}
I have the contents I want to write to a file saved in Strings in my Java program. I need o write them to a .txt file and then compress them into a .gz archive. I'm able to do all of this, but when I extract the file from the .gz archive, the extracted file no longer bear's the .txt file extension.
This is my code below:
private void fillFileBody(OutputStream outputStream) throws IOException {
Scanner scanner = new Scanner(new ByteArrayInputStream(this.fileBody.getBytes()));
while(scanner.hasNextLine()){
outputStream.write((scanner.nextLine() + "\n").getBytes());
}
scanner.close();
}
public void writeFileContentsToDisk(){
GZIPOutputStream gZipOutStream = null;
FileOutputStream initialTxtFileOutStream = null;
FileInputStream initialTxtFileInStream = null;
String txtFile = this.fileName + ".txt";
try {
initialTxtFileOutStream = new FileOutputStream(txtFile);
initialTxtFileOutStream.write((this.fileHeader).getBytes());
fillFileBody(initialTxtFileOutStream);
initialTxtFileOutStream.write(this.fileTrailer.getBytes());
initialTxtFileInStream = new FileInputStream(txtFile);
gZipOutStream = new GZIPOutputStream(new FileOutputStream(this.fileName + ".gz"));
byte[] buffer = new byte[1024];
int length;
while ((length = initialTxtFileInStream.read(buffer)) > 0) {
gZipOutStream.write(buffer, 0, length);
}
} catch (Exception e) {
LOGGER.error("Error writing file: " + Logger.getStackTrace(e));
}
try {
gZipOutStream.close();
initialTxtFileOutStream.close();
initialTxtFileInStream.close();
} catch (IOException e) {
LOGGER.warn("Error closing i/o streams involved in writing file: " + Logger.getStackTrace(e));
}
}
I wrote the sample code below and used x.c as input from my working directory. x.c.gz was the output file. I used gunzip on x.c.gz and it produced a file with the name x.c and so it seemed to work fine.
package compress;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
/**
*
* #author srikanthn
*/
public class Compress {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
compressFile(args[0]);
}
public static void compressFile(String file){
GZIPOutputStream gZipOutStream = null;
FileInputStream initialTxtFileInStream = null;
String txtFile = file;
try {
initialTxtFileInStream = new FileInputStream(txtFile);
gZipOutStream = new GZIPOutputStream(new FileOutputStream(txtFile+ ".gz"));
byte[] buffer = new byte[1024];
int length;
while ((length = initialTxtFileInStream.read(buffer)) > 0) {
gZipOutStream.write(buffer, 0, length);
}
} catch (IOException e) {
System.out.println("Error writing file: " + e.getStackTrace());
}
try {
gZipOutStream.close();
initialTxtFileInStream.close();
} catch (IOException e) {
System.out.println("Error closing i/o streams involved in writing file: " + e.getStackTrace());
}
}
}
I have a download button in my webpage where when i click it, it downloads a zip file. now i want to have a function like, when i click the download button the zip file should automatically extract and save in a user defined folder.
i have an idea that if we can create a exe file and add it to the download button then it should automatically extract the zip file and save in folder
%>
<td align="center">
<img onclick="pullReport('<%=reportPath.toString()%>');" title="Click to download this Report" src="./images/down-bt.gif"/>
</td>
</tr>
<%} %>
this is the method that creates zip file
public ActionForward pullReport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws SQLException{
Connection connection=null;
boolean cont=false;
failureList.clear();
logger.info("dispatch = pullReport");
String filePaths=null;
String filePath = null;
String fileName = null;
String srcFileName = null;
String directory = null;
try{
Properties props = Application.getProperties();
String basePath = props.getProperty("std.report_location");
logger.info(" basepath " + basePath);
connection=ConnectionManager.getConnection();
StandardReportsForm standardReportsForm=(StandardReportsForm)form;
filePaths=standardReportsForm.getFilePath();
logger.info("filepaths " + filePaths);
ServletOutputStream fos = null;
InputStream is = null;
String [] filePathArr = filePaths.split(",");
FileIO fio = null;
FileIO srcFio = null;
if (filePathArr.length > 1) {
filePath = filePathArr[0].substring(0,filePathArr[0].lastIndexOf("."))+".zip";
logger.info(filePath + " creating zip file ......");
directory = basePath+filePath.substring(0,filePath.lastIndexOf('/'));
logger.info( " Direcory Name :" +directory);
fileName = filePath.substring(filePath.lastIndexOf('/')+1);
logger.info( " File Name :" +fileName);
fio = new FileIO(directory,fileName);
fio.mkDir();
byte[] buffer = new byte[1024];
OutputStream fosForZip = fio.createOutputStream();
ZipOutputStream zos = new ZipOutputStream(fosForZip);
InputStream fis = null;
for (int i=0; i < filePathArr.length; i++) {
srcFileName = filePathArr[i].substring(filePathArr[i].lastIndexOf('/')+1);
srcFio = new FileIO(directory,srcFileName);
if (srcFio.isFileExist()) {
cont=true;
logger.info(" adding into zip file " +srcFileName);
fis = srcFio.createInputStream();
BufferedInputStream bis = new BufferedInputStream(fis);
zos.putNextEntry(new ZipEntry(srcFileName));
int length;
while ((length = bis.read(buffer)) != -1) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
bis.close();
srcFio.closeInputStream(fis);
} else {
logger.info(srcFileName + " file does not exist on shared drive");
cont =false;
break;
}
}
FileIO.closeOutputStream(zos);
if (!cont){
standardReportsForm.setMissingFileName(srcFileName);
request.getSession().getAttribute("fetchReports");
standardReportsForm.setFetchedReports((List<ReportDetails>)request.getSession().getAttribute("fetchReports"));
return mapping.findForward("fetchReport");
}
} else {
filePath = filePathArr[0];
fileName = filePath.substring(filePath.lastIndexOf('/')+1);
}
if (basePath.startsWith("smb")) {
SmbFile smbFile = new SmbFile(basePath+filePath,SMBHelper.getInstance().createAuthFromSmbLocation(basePath));
if(smbFile.exists())
{
is = new SmbFileInputStream(smbFile);
cont=true;
}
} else {
File file=new File(basePath+filePath);
if(file.exists())
{
is = new FileInputStream(file);
cont=true;
}
}
if(cont)
{
fos=response.getOutputStream();
setContentType(response, fileName);
//fos.write (baos.toByteArray());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = is.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
byte[] bytes = bos.toByteArray();
fos.write(bytes);
fos.flush();
fos.close();
} else {
standardReportsForm.setMissingFileName(fileName);
request.getSession().getAttribute("fetchReports");
standardReportsForm.setFetchedReports((List<ReportDetails>)request.getSession().getAttribute("fetchReports"));
return mapping.findForward("fetchReport");
}
}catch(SQLException sx) {
logger.error(" error log SQLException " ,sx);
failureList.add(new UROCException(UROCMessages.getMessage("ERR_CONN_EXEC"), sx));
} catch(NamingException ne) {
logger.info("RMI error is "+ne);
failureList.add(new UROCException(UROCMessages.getMessage("ERR_NAMING_EXEC"), ne));
} catch(Exception e) {
logger.error(" error log Exception " ,e);
failureList.add(new UROCException(UROCMessages.getMessage("ERR_GEN_EXEC", new String[] {"General Exception"}), e));
} finally {
SQLHelper.closeConnection(connection, failureList, logger);
}
return null;
}
yah you can use java code to unzip the file.here is the example
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipUtility {
public String zipFilePath= "D:/javatut/corejava/src/zipfile.zip";
public String destDir = "D:/javatut/corejava";
private static final int BUFFER_SIZE = 4096;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
UnzipUtility uu = new UnzipUtility();
uu.unzip(uu.zipFilePath, uu.destDir);
}
public void unzip(String zipFilePath,String destDir)throws IOException{
File destDirectory = new File(destDir);
if(!destDirectory.exists()){
destDirectory.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry zipEntry = zipIn.getNextEntry();
while(zipEntry!=null){
String filePath=destDir+File.separator+zipEntry.getName();
if(!zipEntry.isDirectory()){
extractFile(zipIn,filePath);
}
else{
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
zipEntry = zipIn.getNextEntry();
}
zipIn.close();
}
private void extractFile(ZipInputStream zipIn, String filePath) throws FileNotFoundException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
try {
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
thank you.......
please follow this path and (clear) automatic files viewer
chrome://settings/onStartup/Advanced/Downloads/automatic file viewer (clear)
I am trying to create a folder for each username a user logs in as. Currently I have
private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
File theFile = new File(destination + username); // will create a sub folder for each user
but the File theFile bit does not create a new folder for the username. How would I do this ?
I have tried
private String destination;
public void File()
{
destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
File theFile = new File(destination + username); // will create a sub folder for each user (currently does not work, below hopefully is a solution)
theFile.mkdirs();
}
but I need to use the destination later on in the program, how would I do that?
This is my whole code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package richard.fileupload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import java.io.File;
import org.primefaces.event.FileUploadEvent;
#ViewScoped
#ManagedBean(name = "fileUploadController")
public class FileUploadController {
/*
public void handleFileUpload(FileUploadEvent event) {
System.out.println("called");
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
*/
private String username;
private String destination;
#PostConstruct
public void init() {
System.out.println("called get username");
username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
}
public void File() {
destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
File theFile = new File(destination + username); // will create a sub folder for each user (currently does not work, below hopefully is a solution)
theFile.mkdirs();
}
public File getDirectory(String destination, String username) {
System.out.println("called get directory");
// currently not working, is not calling the username or destination
//set the user directory from the destinarion and the logged user name
File directory = new File(destination, username);
//check if the location exists
if (!directory.exists()) {
//let's try to create it
try {
directory.mkdir();
} catch (SecurityException secEx) {
//handle the exception
secEx.printStackTrace(System.out);
directory = null;
}
}
return directory;
}
public void handleFileUpload(FileUploadEvent event) {
System.out.println("called handle file");
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded."); //Displays to user on the webpage
FacesContext.getCurrentInstance().addMessage(null, msg);
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
} catch (IOException e) {
//handle the exception
e.printStackTrace();
}
}
public void copyFile(String fileName, InputStream in) {
try {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(destination + fileName)); // cannot find path when adding username atm
System.out.println("Called CopyFile"); //testing
System.out.println(destination + fileName);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
//make sure new file is created, (displays in glassfish server console not to end user)
System.out.println("New file created!");//testing
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage("The files were not uploaded!");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
}
FINAL EDIT (Hopefully)
public void copyFile(String fileName, InputStream in) {
try {
destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
File theFile = new File(destination + "/" + username);
theFile.mkdirs();// will create a sub folder for each user (currently does not work, below hopefully is a solution) (DOES NOW WORK)
System.out.println("Completed File");
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(destination + fileName)); // cannot find path when adding username atm
System.out.println("Called CopyFile"); //testing
System.out.println(destination + fileName);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
//make sure new file is created, (displays in glassfish server console not to end user)
System.out.println("New file created!");//testing
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage("The files were not uploaded!");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
}
Just how can i print out the new destination and use this later on as currently it creates the new folder but does not select it to use
EDIT SOLVED THIS TOO :
NewDestination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/" + username;
Added the above code and now it all works
You have to actually call some method to create the directories. Just creating a file object will not create the corresponding file or directory on the file system.
You can use File#mkdirs() method to create the directory: -
theFile.mkdirs();
Difference between File#mkdir() and File#mkdirs() is that, the later will create any intermediate directory if it does not exist.
Use this code spinet for create intermediate folders if one doesn't exist while creating/editing file:
File outFile = new File("/dir1/dir2/dir3/test.file");
outFile.getParentFile().mkdirs();
outFile.createNewFile();
A nice Java 7+ answer from Benoit Blanchon can be found here:
With Java 7, you can use Files.createDirectories().
For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
If you have a large hierarchy of stacked, non-existent directories, you must first call Files.createDirectories(..). For example, in Kotlin it may look like this:
fun File.createFileWithParentDirectories() {
if(this.exists())return
val parent = this.parentFile
if(!parent.exists()) Files.createDirectories(parent.toPath())
this.createNewFile()
}
Well, I have this program, the download option is working fine. I can access the other computer and download the file from it to my desktop, but the upload is a problem. When I choose the file, the program tries to get the file from the other computer and not mine so the path is wrong. Is there somehow I can use JFileChooser (as I do in download) and put in my computer name or IP address? Before I started to try the access to another computer I did make it work with JFilChooser, but the path messes it up now. Some tips or tricks?
public void upload(String username) throws RemoteException, NullPointerException{
try {
System.out.println(getProperty);
String lol = "/hei/hei.txt";
String ServerDirectory=("//" + "JOAKIM-PC"+ "/Users/Public/Server/");
byte[] filedata = cf.downloadFile2(getProperty + lol);
File file = new File(getProperty + lol);
BufferedOutputStream output = new BufferedOutputStream
(new FileOutputStream(ServerDirectory + file.getName()));
output.write(filedata,0,filedata.length);
output.flush();
output.close();
} catch(Exception e) {
System.err.println("FileServer exception: "+ e.getMessage());
e.printStackTrace();
}
}
public void download(String username) throws RemoteException, NullPointerException{
JFileChooser chooser = new JFileChooser("//" + "JOAKIM-PC" + "/Users/Joakim/Server/");
chooser.setFileView(new FileView() {
#Override
public Boolean isTraversable(File f) {
return (f.isDirectory() && f.getName().equals("Server"));
}
});
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
} try {
String fileName = chooser.getSelectedFile().getName();
File selectedFile = chooser.getSelectedFile();
String clientDirectory = getProperty + "/desktop/";
byte[] filedata = cf.downloadFile(selectedFile);
System.out.println("Byte[] fildata: " + selectedFile);
File file = new File(fileName);
System.out.println("fileName: " + fileName);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(clientDirectory + file.getName()));
output.write(filedata, 0, filedata.length);
output.flush();
output.close();
} catch (Exception e) {
System.err.println("FileServer exception: " + e.getMessage());
e.printStackTrace();
}
}
If I understood well, you want to use on your upload method this code:
JFileChooser chooser = new JFileChooser("./hei/");
int returnval = chooser.showOpenDialog(this);
String ServerDirectory=("//" + "JOAKIM-PC"+ "/Users/Public/Server/");
if(returnval == JFileChooser.APPROVE_OPTION){
File file = chooser.getSelectedFile();
try{
byte[] filedata = cf.downloadFile2(file.getAbsolutePath());
BufferedOutputStream output = new BufferedOutputStream
(new FileOutputStream(ServerDirectory + file.getName()));
output.write(filedata,0,filedata.length);
output.flush();
output.close();
}
catch(Exception e){
e.printStackTrace();
}
}
Is it right for you?