Change directory for uploading file in FTP - java

I need to change the working directory in a Java program where i want to upload a file, but i am not able to change the working directory.
Currently i am using following code please have a look what is going wrong here.
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
public class FileUploadDemo {
public static void main(String[] args) {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("36.109.60.40");
client.login("XYZ", "SYSTEM");
client.enterLocalPassiveMode();
boolean changeWorkingDirectory = client.changeWorkingDirectory("ABC\\QSRC");
if (changeWorkingDirectory)//this is false here
{
String filename = "ATR.CBL";
fis = new FileInputStream("C:\\Users\\RATSYA\\Desktop\\backup\\DINAKE\\ATR.CBL");
boolean storeFile = client.storeFile(filename, fis);
if(storeFile)
System.out.println("file stored");
else
System.out.println("file can not be stored");
client.logout();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Tried "ABC/QSRC" ?
Never used it but some general ideas:
ABC\QSRC exists in ftp directory of user XYZ?
Did you try same login and operation with other client and it works?
maybe you mean /ABC/QSRC

I think I see how you can make this work. you should probably store your directory in a String like so: String dir = "/Server/FTP/OtherDir/"; and than whenever you want to change directory you change that value. You can use the String storing the directory when you want to upload/download a file by doing something like this:
dir ="/Server/FTP/OtherDir/";
yourFileWriter.write(dir + file);
I hope this helps!

Related

Image uploaded in FTP was 0k with FTPClient

I have a problem with image upload from my android mobile phone to a FTP Area, the FTP work fine, i tried some other interaction with it and i don't have any problem.
The uploaded file weight 0k, name and file extension are right, no error or exception. I do a test to copy the file in another folder and the file copied right.
private class FTPUploader extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
String data = "/pathimage/filename.jpg";
File sourceFile = new File(data);
FTPClient con = new FTPClient();
try {
con.connect("ftp.ftpServer.it", 21);
if (con.login("user", "password")) {
con.setFileType(FTP.BINARY_FILE_TYPE);
con.enterLocalPassiveMode();
if (sourceFile.exists()) {
InputStream input = new FileInputStream(sourceFile);
boolean result = con.storeFile("/folder/newfilename.jpg", input);
input.close();
if (result) {
System.out.println(result);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (sourceFile.exists()) {
con.logout();
con.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
What i'm wrong about? it's possible manage the event when the upload is finished? thank you in advance for the support
In the end, I find a workaround that works for me. I use the library ftp4j where I can manage the events of the upload and with the System.out.println I can follow the step and be sure for the right upload.
I post in to follow the code. At first, I need to add the library in the libs folder and import it in the build.gradle(Module:app)
compile files('libs/ftp4j-1.7.2.jar')
next i import what i need in the worksheet:
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
And change the code for ftp4j
private class FTPUploader extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
FTPClient con = new FTPClient();
try {
con.setPassive(true);
con.setType(FTPClient.TYPE_BINARY);
con.connect("ftp.server.it");
con.login("user", "password");
con.changeDirectory("changeFTPUploadDirectory");
con.upload(new java.io.File("/path/local/image"), new MyTransferListener());
} catch (Exception e) {
e.printStackTrace();
}
try {
con.disconnect(true);
} catch (IOException | FTPException | FTPIllegalReplyException e) {
e.printStackTrace();
}
return null;
}
}
But what I find very useful is the event management where if there is some problem you can check where and why upload is stopped.
public class MyTransferListener implements FTPDataTransferListener {
public void started() {
System.out.println("Trasferimento FTP avviato");
}
public void transferred(int length) {
System.out.println("in trasferimento: "+ String.valueOf(length));
}
public void completed() {
System.out.println("Completato");
}
public void aborted() {
System.out.println("Annullato");
}
public void failed() {
System.out.println("Trasferimento fallito");
}
}
As already stated in the top of the post this isn't a solution but a workaround to understand the error.After the edit the code with this change work right. in any way, I search the server-side logs to have more details about my problem. Thank you in advance
documentation -> ftp4j

Java - How can I get the file paths of the contents of a given directory and write them to a text file?

I've found answers to various questions on here before, but this is my first time asking one. I'm kicking around an idea for my final project in my computer programming class, and I'm working on a few proof of concept programs in Java, working in Eclipse. I don't need anything more than to get the filepaths of the contents of a directory and write them to a .txt file. Thanks in advance!
Edit: I am posting my code below. I found a snippet of code to use for getting the contents and print them to the screen, but the print command is a placeholder that I'll replace with a write to folder command when I can.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ScanFolder {
public static void main(String[] args) throws IOException {
Files.walk(Paths.get("C:/Users/Joe/Desktop/test")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
}
}
EDIT: I've enclosed the OutputStreamWriter in a BufferedWriter
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("txt.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
writeContentsOfFileToAFile(new File("."), out, true); // change true to
// false if you
// don't want to
// recursively
// list the
// files
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static void writeContentsOfFileToAFile(File parent, BufferedWriter out, boolean enterIntoDirectory) {
for (File file : parent.listFiles()) {
try {
out.write(file.toString() + "\r\n");
} catch (IOException e) {
e.printStackTrace();
}
if (enterIntoDirectory && file.isDirectory())
writeContentsOfFileToAFile(file, out, enterIntoDirectory);
}
}
Is this what you need?

Checking if properties file exists and has required properties

I have written the code bellow to check if a properties file exists and has the required properties. If it exists it prints the message that the file exists and is intact, if not then it creates the properties file with the required properties.
What I wanted to know is, is there a more elegant way of doing this or is my way pretty much the best way? Also the minor problem that I'm having is that with this way it doesn't check for extra properties that should not be there, is there a way to do that?
Summary of my requirements:
Check if the file exists
Check if it has the required properties
Check if it has extra properties
Create the file with the required properties if it doesn't exist or if there are extra or missing properties
Source files and Netbeans Project download
Source:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
public class TestClass {
public static void main(String[] args) {
File propertiesFile = new File("config.properties");
if (propertiesFile.exists() && propertiesExist(propertiesFile)) {
System.out.println("Properties file was found and is intact");
} else {
System.out.println("Properties file is being created");
createProperties(propertiesFile);
System.out.println("Properties was created!");
}
}
public static boolean propertiesExist(File propertiesFile) {
Properties prop = new Properties();
InputStream input = null;
boolean exists = false;
try {
input = new FileInputStream(propertiesFile);
prop.load(input);
exists = prop.getProperty("user") != null
&& prop.getProperty("pass") != null;
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return exists;
}
public static void createProperties(File propertiesFile)
{
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream(propertiesFile);
prop.setProperty("user", "username");
prop.setProperty("pass", "password");
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
this is my way. (not sure if more elegant, but it can be an inspiration/different aproach)
Try/catch should be enough to see if the file exists or not
try {
loading files etc...
} catch (FileNotFoundException e) {
throw new MojoExecutionException( "[ERROR] File not found", e );
} catch (IOException e) {
throw new MojoExecutionException( "[ERROR] Error reading properties", e );
}
Code that checks your loaded prop:
Properties tmp = new Properties();
for(String key : prop.stringPropertyNames()) {
if(tmp.containsKey(key)){
whatever you want to do...
}
}
I use tmp, a new properties variable, to compare with ,but the key variable will hold a string so in the if statement you can compare it to array of strings and the way you do it is up to you.

commons-net FTPClient.retrieveFileStream() returns wrong result

I have a Problem with commons-net FTPClient. If I download a file from my ftp server wirth retrieveFileStream() it works, but I get the result '150 Opening BINARY mode data connection for ...'. If I call noop() I get '226 Transfer complete' as result. For every following operation I get the result of the prvious operation.
I found out, that FTPClient reads results until end of line, if there are two result lines (as after retrieveFileStream()), I get the second one after the next command. I did a workaround by overriding FTPClient.retrieveFileStream() like this:
public static void main(String[] args){
try {
MyFTPClient ftpClient = new MyFTPClient();
try {
ftpClient.connect(ftphost, 21);
if(!ftpClient.login( ftpuser, ftppassword )){
throw new RuntimeException(ftpClient.getReplyString());
}
if(!ftpClient.changeWorkingDirectory("in")){
throw new RuntimeException(ftpClient.getReplyString());
}
FTPFile[] files = ftpClient.listFiles();
for(FTPFile file: files){
if(file.getName().startsWith(FILENAME) && (file.getType() == FTPFile.FILE_TYPE)){
InputStream in = ftpClient.retrieveFileStream(file.getName());
CsvFile csvFile = new CsvFile(in, "ISO-8859-1", ';', "yyyyMMdd", "#.00", Locale.US, false);
in.close();
in = null;
System.out.println(ftpClient.getReplyString());
System.out.println(ftpClient.readLine());
System.out.println(ftpClient.rnfr(file.getName()));
System.out.println(ftpClient.getReplyString());
System.out.println(ftpClient.rnto("x" + file.getName()));
System.out.println(ftpClient.getReplyString());
}
}
if(!ftpClient.logout()){
throw new RuntimeException(ftpClient.getReplyString());
}
} finally {
ftpClient.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static class MyFTPClient extends FTPClient{
public String readLine(){
try {
__getReplyNoReport();
} catch (IOException e) {
}
return getReplyString();
}
}
The call of the method readLine() gets me the additional Line of result.
But is this a bug of FTPClient or is it a problem of my ftp-server? The Problem of that workaround is, that the method blocks, if there is only one line of response.
Thanx for your help
Stephan
Sometimes it helps, reading the manual. A call of completePendingCommand() works

Why not to delete a file after creating this file with java io api?

I created a file and add some contents into it. Then, I want to delete it with java api. Before this operation, the write out stream is closed, but still failed, so could someone help me to resolve it?
Code snippets:
private static void _saveLogFile(String logContent, String urlPathName) throws Exception {
try {
StringBuilder sb = new StringBuilder("");
sb.append(logContent + "\r\n");
String a = sb.toString();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(urlPathName, true)));
bw.write(a);
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static void _deleteLogFile(String urlPathName) throws Exception {
File file = new File(urlPathName);
if (!file.exists()) {
throw new IllegalArgumentException("Delete: no such file or directory: " + urlPathName);
}
if (file.isDirectory()) {
String[] files = file.list();
if (files.length > 0) {
throw new IllegalArgumentException("Delete: directory is not empty: " + urlPathName);
}
}
boolean success = file.delete();
if (!success) {
throw new IllegalArgumentException("Delete:deletion failed.");
}
}
Your code is correct, but only prone to resource leaking. As long as bw.write(a) doesn't throw an exception, bw.close() will succeed. You should rather do the close in finally block to ensure that it will take place regardless of exceptions.
BufferedWriter bw = null;
try {
bw = new BufferedWriter(...);
bw.write(...);
} finally {
if (bw != null) try { bw.close(); } catch (IOException logOrIgnore) {}
}
Back to the actual problem, the symptoms suggests that something else is still holding the file open. Are you able to delete it from inside the platform's shell (Windows Explorer, etc) while the program is still running? For Windows, there are several tools to check if the file is still locked and if so, by what process.
Process Explorer
OpenedFilesView
WhoLockMe
Here's an SSCCE. Just copy'n'paste'n'run it unchanged. It works fine at my machine. Please run it at yours and alter where necessary so that it matches the actual coding at a minimum which still reproduces/exhibits your problem.
package mypackage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Test {
public static void main(String args[]) throws Exception {
File file = new File("/test.txt");
for (int i = 0; i < 1000; i++) {
write("line" + i, file); // Write "many" lines.
}
System.out.println("File exist before delete? " + file.exists());
System.out.println("File deleted? " + file.delete());
System.out.println("File exist after delete? " + file.exists());
}
public static void write(String line, File file) throws IOException {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
writer.write(line);
} finally {
if (writer != null) try {
writer.close();
} catch (IOException e) {
System.err.println("Close failed!");
e.printStackTrace();
}
}
}
}
Output (as expected):
File exist before delete? true
File deleted? true
File exist after delete? false
Using JDK 1.6.0_21 on Windows XP.
Finally, fix it. These snippets are right definitely. The cause is that another thread opens the generated log file and does not close this stream. So could not delete the generated file.
It is a bug of my team player.
Thanks.

Categories

Resources