i'm new to java programming and am using Apache commons net ftp to upload text files to my ftp server.
however, it seems that i can only upload the files on the same directory as my program .. when i set the file path to something like that : "C:\Users\Packard\Documents\ProjectsJava\FugeLessons\outputFile.txt" , it throws no errors, but when i check the ftp, there is nothing, like it has not been uploaded .
here is the code i'm using :
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;
public class ftp{
private final String host = "ftp.address.com";
private final String user = "user";
private final String pass = "pass";
public static void main(String[] args) {
ftp client = new ftp();
client.FtpUpload("C:\\Users\\Packard\\Documents\\ProjectsJava\\FugeLessons\\outputFile.txt");
}
public String FtpUpload(String filename){
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect(this.host);
client.login(this.user, this.pass);
fis = new FileInputStream(filename);
client.storeFile(filename, fis);
client.logout();
System.out.println("File " + filename + "\t uploaded successfully!");
} catch(IOException e){
error error = new error();
error.setVisible(true);
e.printStackTrace();
} finally {
try {
if ( fis != null) {
fis.close();
}
client.disconnect();
} catch(IOException e){
e.printStackTrace();
}
}
String ret = "success";
return ret;
}
}
what am i doing wrong ?
Thanks for your help!
You can use ftpClient method getReplyString() to get the error message. Below code can help.
boolean isSendSucces = ftpClient.storeFile(fileName, input );
if( isSendSuccess )
{
System.out.println("Sent File: " + fileName);
}
else
{
System.out.println("Problem is sending File: " + ftpClient.getReplyString());
}
Related
I have a URL i.e http://downloadplugins.verify.com/Windows/SubAngle.exe .
If I paste it on the tab and press enter then the file (SubAngle.exe) is getting downloaded and saved in the download folder. This is a manual process. But it can be done with java code.
I wrote the code for getting the absolute path with the help of the file name i.e SubAngle.exe.
Requirement:- With the help of the URL file gets downloaded,Verify the file has been downloaded and returns the absolute path of the file.
where locfile is "http://downloadplugins.verify.com/Windows/SubAngle.exe"
public String downloadAndVerifyFile(String locfile) {
File fileLocation = new File(locfile);
File fileLocation1 = new File(fileLocation.getName());
String fileLocationPath = null;
if(fileLocation.exists()){
fileLocationPath = fileLocation1.getAbsolutePath();
}
else{
throw new FileNotFoundException("File with name "+locFile+" may not exits at the location");
}
return fileLocationPath;
}
easy and general function that im using:
import org.apache.commons.io.FileUtils;
public static void downLoadFile(String fromFile, String toFile) throws MalformedURLException, IOException {
try {
FileUtils.copyURLToFile(new URL(fromFile), new File(toFile), 60000, 60000);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("exception on: downLoadFile() function: " + e.getMessage());
}
}
Instead of writing this huge code, go for Apache's commons.io
Try this:
URL ipURL = new URL("inputURL");
File opFile = new File("outputFile");
FileUtils.copyURLToFile(ipURL, opFile);
Code to DownloadFile from URL
import java.net.*;
import java.io.*;
public class DownloadFile {
public static void main(String[] args) throws IOException {
InputStream in = null;
FileOutputStream out = null;
try {
// URL("http://downloadplugins.verify.com/Windows/SubAngle.exe");
System.out.println("Starting download");
long t1 = System.currentTimeMillis();
URL url = new URL(args[0]);
// Open the input and out files for the streams
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
out = new FileOutputStream("YourFile.exe");
// Read data into buffer and then write to the output file
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
long t2 = System.currentTimeMillis();
System.out.println("Time for download & save file in millis:"+(t2-t1));
} catch (Exception e) {
// Display or throw the error
System.out.println("Erorr while execting the program: "
+ e.getMessage());
} finally {
// Close the resources correctly
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Configure the value of fileName properly to know where the file is getting stored.
Source: http://www.devmanuals.com/tutorials/java/corejava/files/java-read-large-file-efficiently.html
The source was modified to replace local file with http URL
Output:
java DownloadFile http://download.springsource.com/release/TOOLS/update/3.7.1.RELEASE/e4.5/springsource-tool-suite-3.7.1.RELEASE-e4.5.1-updatesite.zip
Starting download
Time for download & save file in millis:100184
My problem is need to transfer files from one remote server to another remote server (may be FTP/SFTP) but there is no direct method to transfer files from one remote server to another.
That's why I am downloading files from server to local temp.
After uploading to local to another server. After uploading I need to remove local temp folder but the files and the folder is not deleted.
Can you please help us in this regard?
My code is
package FTPTransfer;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.File;
import java.util.Calendar;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import com.jcraft.jsch.*;
public class FtpToSftp
{
JSch sftp=null;
ChannelSftp channelSftp=null;
Channel channel=null;
FTPClient ftp = null;
Session session=null;
String SFTP_ROOT="/Mahesh/";
String FTP_ROOT="/Mahesh/";
String Local_Dir="./Temp/";
int count=0;
public void ftpconnect(String host, String user, String pwd) throws Exception{
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(host);
if(ftp.isConnected())
System.out.println("FTP Connected");
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(user, pwd);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
}
public void sftpconnect(String host, String user, String pwd) throws Exception{
sftp=new JSch();
session=sftp.getSession(user,host,22);
session.setPassword(pwd);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
if(session.isConnected())
System.out.println("SFTP Session Connected");
channel = session.openChannel("sftp");
channel.connect();
if(channel.isConnected())
System.out.println("SFTP Channel Connected");
channelSftp=(ChannelSftp)channel;
}
public void downloadFromFTP()throws Exception {
File f=new File(Local_Dir);
if(!f.exists())
f.mkdir();
FTPFile[] files = ftp.listFiles(FTP_ROOT);
count=0;
OutputStream outputStream=null;
for (FTPFile fname : files) {
if (fname.getType() == FTPFile.FILE_TYPE) {
System.out.println(fname.getName());
File downloadFile = new File(Local_Dir+ fname.getName());
outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
boolean success = ftp.retrieveFile(FTP_ROOT+fname.getName(), outputStream);
if(success)
count++;
else
downloadFile.delete();
}
}
if(count==files.length)
System.out.println("Files Downloaded Successfully");
System.out.println("count:"+count+"files length:"+files.length);
outputStream.close();
}
public void uploadToSFTP() throws Exception{
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;//0 based
String foldername=month+""+year+"/";
String fullDirPath=SFTP_ROOT+foldername;
SftpATTRS attrs=null;
try{
attrs=channelSftp.lstat(fullDirPath);
}
catch(Exception e){
}
if(attrs==null)
{
channelSftp.mkdir(fullDirPath);
channelSftp.cd(fullDirPath);
}
count=0;
File f1 = new File(Local_Dir);
File list[] = f1.listFiles();
for(File fname : list) {
System.out.println(fname);
channelSftp.put(fname+"", fullDirPath+fname.getName(), ChannelSftp.OVERWRITE);
}
if(count==f1.length())
System.out.println("Files Uploaded Successfully");
}
public FtpToSftp() throws Exception{
System.out.println("Connecting to FTP");
ftpconnect("10.219.28.110", "webteam", "web$123");
System.out.println("Connecting to SFTP");
sftpconnect("10.219.29.61","root" , "leo$123");
downloadFromFTP();
if(ftp.logout()){
ftp.disconnect();
System.out.println("FTP connection closed");
}
uploadToSFTP();
channelSftp.disconnect();
}
public static final void main(String[] args)
{
try{
FtpToSftp fs=new FtpToSftp();
File file=new File(fs.Local_Dir);
if(file.isDirectory())
{
File[] files = file.listFiles();
for (File f : files)
{
String fname=f.getName();
boolean success=f.delete();
if(success)
System.out.println(fname+" file deleted from local");
}
}
if(file.delete())
System.out.println("Temp folder deleted from local");
}
catch(Exception e){
e.printStackTrace();
}
} // end main
}
You can use Apache FTPClient to do this and all other common commands needed with FTP.
Example to delete a folder:
FTPClient client = new FTPClient();
client.connect(host, port);
client.login(loginname, password);
client.removeDirectory(directoryPathOnServer);
client.disconnect();
Here is a code snippet that deletes all the contents of the directory and the directory itself..
private void deleteDirectory(String path,FTPClient ftpClient) throws Exception{
FTPFile[] files=ftpClient.listFiles(path);
if(files.length>0) {
for (FTPFile ftpFile : files) {
if(ftpFile.isDirectory()){
logger.info("trying to delete directory "+path + "/" + ftpFile.getName());
deleteDirectory(path + "/" + ftpFile.getName(), ftpClient);
}
else {
String deleteFilePath = path + "/" + ftpFile.getName();
logger.info("deleting file {}", deleteFilePath);
ftpClient.deleteFile(deleteFilePath);
}
}
}
logger.info("deleting directory "+path);
ftpClient.removeDirectory(path);
}
If you want to delete an directory in your system
This is an part of example:
File x=new File("C:\Users\satyamahesh\folder");
String[]entries = x.list();
for(String s: entries){
File currentFile = new File(x.getPath(), s);
currentFile.delete();
}
Then your folder is deleted.
If you want test it success or don't success to download a folder
Please test Ad Fundum's answer.
Example to delete a folder: (#SatyaMahesh In this part your code is incorrect and this code used NIO is correct.):
File downloadFile = new File(Local_Dir+ fname.getName());
outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
boolean success = ftp.retrieveFile(FTP_ROOT+fname.getName(), outputStream);
if(success)
count++;
else{
Path path = Paths.get("data/subdir/logging-moved.properties");
try {
Files.delete(path);
} catch (IOException e) {
//deleting file failed
e.printStackTrace();
}
}
Then your folder is deleted.
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()
}
I have created zip file using java as below snippet
import java.io.*;
import java.util.zip.*;
public class ZipCreateExample {
public static void main(String[] args) throws IOException {
System.out.print("Please enter file name to zip : ");
BufferedReader input = new BufferedReader
(new InputStreamReader(System.in));
String filesToZip = input.readLine();
File f = new File(filesToZip);
if(!f.exists()) {
System.out.println("File not found.");
System.exit(0);
}
System.out.print("Please enter zip file name : ");
String zipFileName = input.readLine();
if (!zipFileName.endsWith(".zip"))
zipFileName = zipFileName + ".zip";
byte[] buffer = new byte[18024];
try {
ZipOutputStream out = new ZipOutputStream
(new FileOutputStream(zipFileName));
out.setLevel(Deflater.DEFAULT_COMPRESSION);
FileInputStream in = new FileInputStream(filesToZip);
out.putNextEntry(new ZipEntry(filesToZip));
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
in.close();
out.close();
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
System.exit(0);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
System.exit(0);
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(0);
}
}
}
Now I want when I click on the zip file it should prompt me to type password and then decompress the zip file.
Please any help,How should I go further?
Try the following code which is based on Zip4j:
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
public class Zipper
{
private String password;
private static final String EXTENSION = "zip";
public Zipper(String password)
{
this.password = password;
}
public void pack(String filePath) throws ZipException
{
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
zipParameters.setPassword(password);
String baseFileName = FilenameUtils.getBaseName(filePath);
String destinationZipFilePath = baseFileName + "." + EXTENSION;
ZipFile zipFile = new ZipFile(destinationZipFilePath);
zipFile.addFile(new File(filePath), zipParameters);
}
public void unpack(String sourceZipFilePath, String extractedZipFilePath) throws ZipException
{
ZipFile zipFile = new ZipFile(sourceZipFilePath + "." + EXTENSION);
if (zipFile.isEncrypted())
{
zipFile.setPassword(password);
}
zipFile.extractAll(extractedZipFilePath);
}
}
FilenameUtils is from Apache Commons IO.
Example usage:
public static void main(String[] arguments) throws ZipException
{
Zipper zipper = new Zipper("password");
zipper.pack("encrypt-me.txt");
zipper.unpack("encrypt-me", "D:\\");
}
Standard Java API does not support password protected zip files. Fortunately good guys have already implemented such ability for us. Please take a look on this article that explains how to create password protected zip.
(The link was dead, latest archived version: https://web.archive.org/web/20161029174700/http://java.sys-con.com/node/1258827)
Sample code below will zip and password protect your file.
This REST service accepts bytes of the original file. It zips the byte array and password protects it. Then it sends bytes of password protected zipped file as response. The code is a sample of sending and receiving binary bytes to and from a REST service, and also of zipping a file with password protect. The bytes are zipped from stream, so no files are ever stored on the server.
Uses JAX-RS API using Jersey API in java
Client is using Jersey-client API.
Uses zip4j 1.3.2 open source library, and apache commons io.
#PUT
#Path("/bindata/protect/qparam")
#Consumes(MediaType.APPLICATION_OCTET_STREAM)
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response zipFileUsingPassProtect(byte[] fileBytes, #QueryParam(value = "pass") String pass,
#QueryParam(value = "inputFileName") String inputFileName) {
System.out.println("====2001==== Entering zipFileUsingPassProtect");
System.out.println("fileBytes size = " + fileBytes.length);
System.out.println("password = " + pass);
System.out.println("inputFileName = " + inputFileName);
byte b[] = null;
try {
b = zipFileProtected(fileBytes, inputFileName, pass);
} catch (IOException e) {
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
System.out.println(" ");
System.out.println("++++++++++++++++++++++++++++++++");
System.out.println(" ");
return Response.ok(b, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition", "attachment; filename = " + inputFileName + ".zip").build();
}
private byte[] zipFileProtected(byte[] fileBytes, String fileName, String pass) throws IOException {
ByteArrayInputStream inputByteStream = null;
ByteArrayOutputStream outputByteStream = null;
net.lingala.zip4j.io.ZipOutputStream outputZipStream = null;
try {
//write the zip bytes to a byte array
outputByteStream = new ByteArrayOutputStream();
outputZipStream = new net.lingala.zip4j.io.ZipOutputStream(outputByteStream);
//input byte stream to read the input bytes
inputByteStream = new ByteArrayInputStream(fileBytes);
//init the zip parameters
ZipParameters zipParams = new ZipParameters();
zipParams.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParams.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipParams.setEncryptFiles(true);
zipParams.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
zipParams.setPassword(pass);
zipParams.setSourceExternalStream(true);
zipParams.setFileNameInZip(fileName);
//create zip entry
outputZipStream.putNextEntry(new File(fileName), zipParams);
IOUtils.copy(inputByteStream, outputZipStream);
outputZipStream.closeEntry();
//finish up
outputZipStream.finish();
IOUtils.closeQuietly(inputByteStream);
IOUtils.closeQuietly(outputByteStream);
IOUtils.closeQuietly(outputZipStream);
return outputByteStream.toByteArray();
} catch (ZipException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
IOUtils.closeQuietly(inputByteStream);
IOUtils.closeQuietly(outputByteStream);
IOUtils.closeQuietly(outputZipStream);
}
return null;
}
Unit test below:
#Test
public void testPassProtectZip_with_params() {
byte[] inputBytes = null;
try {
inputBytes = FileUtils.readFileToByteArray(new File(inputFilePath));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("bytes read into array. size = " + inputBytes.length);
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080").path("filezip/services/zip/bindata/protect/qparam");
target = target.queryParam("pass", "mypass123");
target = target.queryParam("inputFileName", "any_name_here.pdf");
Invocation.Builder builder = target.request(MediaType.APPLICATION_OCTET_STREAM);
Response resp = builder.put(Entity.entity(inputBytes, MediaType.APPLICATION_OCTET_STREAM));
System.out.println("response = " + resp.getStatus());
Assert.assertEquals(Status.OK.getStatusCode(), resp.getStatus());
byte[] zipBytes = resp.readEntity(byte[].class);
try {
FileUtils.writeByteArrayToFile(new File(responseFilePathPasswordZipParam), zipBytes);
} catch (IOException e) {
e.printStackTrace();
}
}
Feel free to use and modify. Please let me know if you find any errors. Hope this helps.
Edit 1 - Using QueryParam but you may use HeaderParam for PUT instead to hide passwd from plain sight. Modify the test method accordingly.
Edit 2 - REST path is filezip/services/zip/bindata/protect/qparam
filezip is name of war. services is the url mapping in web.xml. zip is class level path annotation. bindata/protect/qparam is the method level path annotation.
In new version of Zip4j, class Zip4jConstants was removed. Use EncryptionMethod and AesKeyStrength class instead. Documentation : https://github.com/srikanth-lingala/zip4j
ZipParameters zipParameters = new ZipParameters();
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(EncryptionMethod.AES);
zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
List<File> filesToAdd = Arrays.asList(
new File("somefile"),
new File("someotherfile")
);
ZipFile zipFile = new ZipFile("filename.zip", "password".toCharArray());
zipFile.addFiles(filesToAdd, zipParameters);
There is no default Java API to create a password protected file. There is another example about how to do it here.
Library Zip4J seems to be the preferred answer.
In case the privacy of the password is highly recommended, one might close a security gap in class ZipFile, which carries the password in plain text, even after the ZipFile is closed. Following method destroys the password.
public static void destroyZipPassword(ZipFile zip) throws DestroyFailedException
{
try
{
Field fdPwd = ZipFile.class.getDeclaredField("password");
fdPwd.setAccessible(true);
char[] password = (char[]) fdPwd.get(zip);
Arrays.fill(password, (char) 0);
}
catch (Exception e)
{
e.printStackTrace();
throw new DestroyFailedException(e.getMessage());
}
}
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPFile;
import java.io.*;
public class FTPUpload{
public static boolean uploadfile(String server,String username,String Password,String source_file_path,String dest_dir){
FTPClient ftp=new FTPClient();
try {
int reply;
ftp.connect(server);
ftp.login(username, Password);
System.out.println("Connected to " + server + ".");
System.out.print(ftp.getReplyString());
reply = ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP server refused connection.");
return false;
}
System.out.println("FTP server connected.");
InputStream input= new FileInputStream(source_file_path);
ftp.storeFile(dest_dir, input);
System.out.println( ftp.getReplyString() );
input.close();
ftp.logout();
} catch(Exception e) {
System.out.println("err");
e.printStackTrace();
return false;
} finally {
if(ftp.isConnected()) {
try {
ftp.disconnect();
} catch(Exception ioe) {
}
}
}
return true;
}
public static void main(String[] args) {
FTPUpload upload = new FTPUpload();
try {
upload.uploadfile("192.168.0.210","muruganp","vm4snk","/home/media/Desktop/FTP Upload/data.doc","/fileserver/filesbackup/Emac/");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Am using the above code to upload a file named "data.doc" in the server location 192.168.0.210.
The destination location of my server is fileserver/filesbackup/Emac/.
But I end up receiving the error "553 Could not create file" although the server gets connected successfully. I suspect that I am giving the destination format in a wrong way. Kindly let me know what has to be done to resolve the issue?
The problem is that you try to upload the file to a directory. You should rather specifiy the destination filename, not the destination directory.
Does it work when you try the same in another FTP client?
[Update]
Here is some (untested, since I don't have an FTP server) code that does the error handling better and in a shorter form.
package so3972768;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
public class FtpUpload {
private static void check(FTPClient ftp, String cmd, boolean succeeded) throws IOException {
if (!succeeded) {
throw new IOException("FTP error: " + ftp.getReplyString());
}
}
private static String today() {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}
public void uploadfile(String server, String username, String Password, String sourcePath, String destDir) throws IOException {
FTPClient ftp = new FTPClient();
ftp.connect(server);
try {
check(ftp, "login", ftp.login(username, Password));
System.out.println("Connected to " + server + ".");
InputStream input = new FileInputStream(sourcePath);
try {
String destination = destDir;
if (destination.endsWith("/")) {
destination += today() + "-" + new File(sourcePath).getName();
}
check(ftp, "store", ftp.storeFile(destination, input));
System.out.println("Stored " + sourcePath + " to " + destination + ".");
} finally {
input.close();
}
check(ftp, "logout", ftp.logout());
} finally {
ftp.disconnect();
}
}
public static void main(String[] args) throws IOException {
FtpUpload upload = new FtpUpload();
upload.uploadfile("192.168.0.210", "muruganp", "vm4snk", "/home/media/Desktop/FTP Upload/data.doc", "/fileserver/filesbackup/Emac/");
}
}