File is copied on the FTP server not moved in java - java

Using below program i am able to upload zip file on ftp server.
But it makes the copy of the zip file and upload the file on ftp server.
I want it should delete the file from local system and copy it to server i.e. it should move the file not copy.Please guide
public class UploadFile {
public static void main(String args[])
{
FTPClient ftp=new FTPClient();
try {
int reply;
ftp.connect("ipadddress");
ftp.login("abc", "abc");
reply = ftp.getReplyCode();
System.out.println("reply1" + reply);
if(!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
}
System.out.println("FTP server connected.");
ftp.setFileType(FTP.BINARY_FILE_TYPE);
InputStream input= new FileInputStream("D:\\testencrypted.zip");
String dirTree="/Vel";
boolean dirExists = true;
String[] directories = dirTree.split("/");
for (String dir : directories )
{
if (!dir.isEmpty() )
{
if (dirExists)
{
dirExists = ftp.changeWorkingDirectory(dir);
}
else if (!dirExists)
{
System.out.println("dir tree" + ftp.printWorkingDirectory());
if (!ftp.makeDirectory(dir))
{
throw new IOException("Unable to create remote directory '" + dir + "'. error='" + ftp.getReplyString()+"'");
}
if (!ftp.changeWorkingDirectory(dir))
{
throw new IOException("Unable to change into newly created remote directory '" + dir + "'. error='" + ftp.getReplyString()+"'");
}
System.out.println("dir tree" + ftp.printWorkingDirectory());
}
}
}
ftp.storeFile(dirTree+"/t1.zip",input);
input.close();
ftp.logout();
}
catch(Exception e)
{
System.out.println("err"+ e);
}
finally
{
if(ftp.isConnected())
{
try
{
ftp.disconnect();
}
catch(Exception ioe)
{
}
}
}
}
}

So, once you've completed the upload (and you're sure that it was sucessful, simply use File.delete() to remove the file from the local disk.
File sourceFile = new File("D:\\testencrypted.zip");
InputStream input= new FileInputStream(sourceFile);
// Upload the file...
// Make sure you close the input stream first ;)
if (!sourceFile.delete()) {
System.out.println("Failed to delete " + sourceFile + " from local disk");
sourceFile.deleteOnExit(); // try and delete on JVM exit...
}

Related

Simple file delete code is not working in Java [duplicate]

This question already has answers here:
Java 'file.delete()' Is not Deleting Specified File
(8 answers)
Closed 5 years ago.
Here is my code of deleting the pdf file
try {
File file = new File(docObjectId + ".pdf");
file.setWritable(true);
System.out.println(file.length());
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
It goes to the else part of the code.
PDF file is in project root folder and I am able to delete it manually. Scratching my head now.
Here is complete method. It might be due to some other reason
public Response getContractDocument(#PathParam("docid") String docObjectId) throws Exception {
DocumentumService documentumService = new DocumentumService(documentumConfigUtil);
DocumentumDocumentBean docDocumentBean = documentumService.getContractDocContent(docObjectId, true);
FileInputStream fileInputStream;
fileInputStream = new FileInputStream(docDocumentBean.getDocFile());
compressPdf(fileInputStream,docObjectId + ".pdf");
fileInputStream = new FileInputStream(docObjectId + ".pdf");
ResponseBuilder responseBuilder = Response.ok((Object) fileInputStream);
try {
File file = new File(docObjectId + ".pdf");
System.out.println(file.getAbsolutePath());
file.setWritable(true);
System.out.println(file.length());
File d = new File(file.getAbsolutePath());
if (d.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch(Exception e) {
e.printStackTrace();
}
return responseBuilder.build();
}
My experience is with windows. The reason that a file won't delete is always the same. Some object has a connection to the file and is holding it open. In this case, it looks like it might be fileInputStream.
Try this before you attempt to delete:
fileInputStream.close();
Change if(file.delete) to
try {
file.delete();
System.out.println("file deleted");
} catch(IOException e) {
System.out.println("file not deleted");
}
The exception may not be accurate.
First, check if the file exist or not and then delete it.
Kindly use the below code. Its working fine and is very clear approach for deletion. I hope it would help.
public static void main(String[] args) {
try{
File file = new File("C:/Users/Tehmina Yaseen/Documents/NetBeansProjects/FileDeletion/src/filedeletion/Myfile.pdf");
if (file.exists()) {
file.delete();
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the output:

setPermission in java ftp

I am trying to create a directory on FTP server and upload a file in that directory. The Directory is created successfully but file is not uploaded may be due to write permission
FTPClient ftpClient = new FTPClient();
public void ftpConnection(){
try {
ftpClient.connect(server,port);
ftpClient.enterLocalPassiveMode();
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Operation failed. Server reply code: " + replyCode);
}
boolean success = ftpClient.login(user, pass);
if (!success) {
System.out.println("Could not login to the server");
} else {
System.out.println("LOGGED IN SERVER");
boolean created = ftpClient.makeDirectory("/usr/prtsim");
int returnCode = ftpClient.getReplyCode();
System.out.println(returnCode);
if(created){
System.out.println("created");
ftpClient.changeWorkingDirectory("/usr/prtsim");
uploadFile();
}
else{
if (returnCode == 550)
System.out.println("Directory already present");
else
System.out.println("not created");
}
ftpClient.logout();
ftpClient.disconnect();
}
}
catch(IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
}
public void uploadFile() throws FileNotFoundException, IOException{
File firstLocalFile = new File("C:\\Users\\sswaroo\\Desktop\\sampletext.txt");
//ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
String firstRemoteFile = "sampletext.txt";
InputStream inputStream = new FileInputStream(firstLocalFile);
System.out.println("Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
if (done) {
System.out.println("The first file is uploaded successfully.");
}
}
}
I am getting following response:
LOGGED IN SERVER
257
created
Start uploading first file
The first file is uploaded successfully.
Could you please help me in setting the write permission on directory I created?
Based on your output it looks like you never reach the line
System.out.println("Start uploading first file");
The call
new FileInputStream(firstLocalFile)
will throw a FileNotFoundException if the file passed to it cannot be accessed.
I'd suggest checking to see if the file created at the start of your method is correct and accessible.

Deploying GWT application on Apache Tomcat

On a server side I have a class that I use for convertion SVG file to PDF.
public class PdfHandler {
private File savedFile;
private File svgTempFile;
public PdfHandler(String fileName) {
this.savedFile = new File(File.separator + "documents" + File.separator + fileName);
}
public void convertToPdf(String inputFileName) {
this.svgTempFile = new File(inputFileName);
System.out.println(inputFileName);
if (this.svgTempFile.exists()){
System.out.println("Svg File exists");
}
else {
System.out.println("Svg File not exists");
}
try {
Transcoder transcoder = new PDFTranscoder();
System.out.println("Transcoder created");
FileInputStream fis = new FileInputStream(this.svgTempFile);
System.out.println("Input stream created");
FileOutputStream fos = new FileOutputStream(this.savedFile);
System.out.println("Output stream created");
TranscoderInput transcoderInput = new TranscoderInput(fis);
System.out.println("Transcoder input created");
TranscoderOutput transcoderOutput = new TranscoderOutput(fos);
System.out.println("Transcoder output created");
transcoder.transcode(transcoderInput, transcoderOutput);
System.out.println("Conversion finished");
fis.close();
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Exception");
} finally {
this.svgTempFile.delete();
System.out.println("File deleted");
}
System.out.println("End of method");
}
}
And I have a method that called by RPC.
public String generatePdf(PayDoc filledDoc) {
//String svgFileName = this.generateSvg(filledDoc);
//String pdfFileName = this.generateFileName("pdf");
PdfHandler pdfHandler = new PdfHandler("myPdf.pdf");
pdfHandler.convertToPdf(File.separator + "documents" + File.separator + "mySvg.svg");
return null;//pdfFileName;
}
In eclipse all works fine, but not on Tomcat. RPC fails when I call it on Tomcat
This is Tomcat console output:
\documents\mySvg.svg
Svg File exists
Transcoder created
Input stream created
Output stream created
Transcoder input created
Transcoder output created
File deleted
After that in "documents" folder I have "mySvg.svg"(still not deleted) and "myPdf.pdf"(it is empty).
Looks like you're not including the required library in your deployed application.
ElementTraversal is part of xml-apis-X.XX.X.jar and has to be bundled with your application.
As there are loads of build tools and I don't know which one you're using, I can't suggest changes.

Uploading a file in a specific path of an FTP server [duplicate]

This question already has answers here:
FtpClient storeFile always return False
(5 answers)
Closed 8 years ago.
I want to upload a file in a specific path in an ftp server the code is quite simple:
public static void main(String[] args) {
String server = "xx.xx.xx.xx";
String user = "xxx";
String pass = "xxx";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server);
System.out.println("Connected to " + server + ".");
System.out.print(ftpClient.getReplyString());
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// uploads first file using an InputStream
File firstLocalFile = new File("/tmp/PAR.TXT");
String firstRemoteFile = "/DATA/OUTFILES/PAR.TXT";
InputStream inputStream = new FileInputStream(firstLocalFile);
System.out.println("Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
System.out.println("done:"+done);
inputStream.close();
if (done) {
System.out.println("The file is uploaded successfully.");
}
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I always get done = false.
Here's the result:
Connected to xx.xx.xx.xx.
220 "Welcome (logging activated)"
Start uploading file
done:false
I printed the FtpClient#getReplyCode(). and i get this:
500 Illegal PORT command.
You can only access files relative to the root folder of the ftp server. You need to configure your ftp server to add a virtual folder pointing to the path you want.
I passed to PassiveMode and it works now

Unable to download files from FTP server

I've created Java function that downloads files from FTP server. It works fine from my local machine. But I need to run it under linux server (means another host and port). And the function gives an error
The collection, array, map, iterator, or enumeration portion of a for statement cannot be null
Caused in a line with the code:
for(String f : ftpNames) {
ftpclient.retrieveFile(f, os); // os is OutputStream
}
So it doesn't see the files...
I added
ftpclient.enterRemotePassiveMode();
And ftpclient.getPassiveHost() returns 227 Entering Passive Mode (x,x,x,x,204,15)
Tried to list and download them via shell - it works.
How should I modify my code to solve the problem? Thanks.
UPD. I got log from FTP server I'm trying to get files from, and there is such string:
425 Cannot open data connection
Full code:
static boolean ftpFilesDownload(String ip, int port, String login, String passwd, String ftpdir, String localdir) throws IOException {
Boolean result = false;
FTPClient client = new FTPClient();
String separator = File.separator;
try {
client.connect(ip, port);
System.out.println(client.getReplyString());
client.login(login, passwd);
System.out.println(client.getReplyString());
client.setControlKeepAliveTimeout(1000*60*5);
client.setControlKeepAliveReplyTimeout(1000*60*5);
client.setFileType(FTP.BINARY_FILE_TYPE);
System.out.println("client setFileType success");
client.changeWorkingDirectory(ftpdir);
System.out.println(client.getReplyString());
client.printWorkingDirectory();
System.out.println("directory changed");
FTPFile[] ftpFiles = client.listFiles();
System.out.println(ftpFiles);
String[] ftpNames = client.listNames();
System.out.println("the files are " + Arrays.toString(ftpNames)); // so null here...
for(String f : ftpNames) {
String localfile = localdir + f;
OutputStream os = new FileOutputStream(localfile);
try {
result = client.retrieveFile(f, os);
System.out.println("DOWNLOADING STARTED);
System.out.println(client.getReplyString());
client.noop();
}
catch(Exception e) {
System.out.println(e);
result = false;
}
finally {
if(os != null)
os.close();
}
}
client.logout();
System.out.println(client.getReplyString());
}
catch(Exception e)
{
System.out.println(e);
result = false;
}
finally
{
try
{
client.disconnect();
}
catch(Exception e)
{
System.out.println(e);
result = false;
}
}
return result;
}
As the error message explains, you're trying to iterate over a null object. You should check for this (or make sure an empty Iterable is used perhaps)
If this is an execptional (error) state, I'd check for this explicitly and throw some kind of runtime exception, e.g.:
if (ftpNames == null) {
throw new IllegalArgumentException("Cannot use a null set of FTP servers");
}
for (String f : ftpNames) {
ftpclient.retrieveFile(f, os); // os is OutputStream
}
Alternatively you could try to continue with no FTP servers, but seems a bit pointless.
Try to use ftpclient.enterLocalActiveMode();

Categories