Apache Commons FTP problems - java

I want to implement a FTP Client with Apache Commons Net only for uploading data.
The Connection and Login to FTP-Server works fine.
But the upload does not work right.
The files are a little to big as the originals.
And the files are damaged.
I tried an image, a video and a textfile. Only the textfile is alright.
Now I see while debugging
boolean tmp=client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
gives me false. So it can not be set. Why?
(Maybe this is not the problem?)
Here a the rest of my code
client=new FTPClient();
try {
int reply;
client.connect(url, port);
reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
client.disconnect();
System.err.println("FTP server refused connection.");
System.exit(1);
}
client.login(user, pw);
boolean xxx=client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
client.setControlKeepAliveTimeout(300);
client.enterLocalPassiveMode();
if (client.isConnected())
{
try {
File file=new File(<FILE>);
FileInputStream inputStream = new FileInputStream(file);
OutputStream outputStream = client.storeFileStream(file.getName());
byte[] buffer = new byte[4096];
int l;
while((l = inputStream.read(buffer))!=-1)
{
outputStream.write(buffer, 0, l);
}
inputStream.close();
outputStream.flush();
outputStream.close();}

Change the following:
boolean xxx=client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
Should be:
boolean xxx=client.setFileType(FTP.BINARY_FILE_TYPE);
You have confused FileTransferModes with FileTypes.
The available FileTypes are:
FTP.ASCII_FILE_TYPE (default)
FTP.BINARY_FILE_TYPE
FTP.EBCDIC_FILE_TYPE
FTP.LOCAL_FILE_TYPE
The available FileTransferModes are:
FTP.STREAM_TRANSFER_MODE (default)
FTP.BLOCK_TRANSFER_MODE
FTP.COMPRESSED_TRANSFER_MODE
I suppose if apache introduced enums for these constant types, then this kind of problem could be avoided, but then the library would not be available to pre-java-5 runtimes.
I wonder how much of an issue java 1.4 compatibility really is.

If only the text file was transferred successfully, I suspect you need to set the binary transfer file type.
See the setFileType method to see how to do this.
The commons-net wiki mentions this is the cause of most file corruption issues.

This work for me, Uploading Image and download after It´s Ok: Using
FTP.LOCAL_FILE_TYPE
this code using logger, replace for you logger or use System.out.println("");
private void cargarData(File filelocal) {
FTPClient client = new FTPClient();
try {
client.connect("URLHOSTFTP", "PORT: DEFAULT 21");
if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
client.disconnect();
logger.error("FTP server refused connection.");
System.exit(1);
}
client.login("USER FTP", "PASS FTP");
boolean type = client.setFileType(FTP.LOCAL_FILE_TYPE);
logger.info("Tipo Aceptado:" + type);
client.setControlKeepAliveTimeout(300);
client.enterLocalPassiveMode();
if (client.isConnected()) {
FileInputStream fis = null;
fis = new FileInputStream(filelocal);
client.storeFile(filelocal.getName(), fis);
client.logout();
if (fis != null) {
fis.close();
}
}
logger.info(client.getReplyString());
} catch (IOException e) {
logger.error("error" + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
logger.error("error" + e.getMessage());
e.printStackTrace();
}
}

Related

how to make the file uploading to ftp faster

we are using below code to upload files back to the FTP server?
basically 60 MB file is taking 3 minutes to upload to ftp server.Is there any way to make it faster?Please note that uploadable file(input file) and ftp server, both are on the same host but still its taking this much time.
at this line client.storeFile(filename, fis) its taking maximum time.
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("ftp.domain.com");
client.login("admin", "secret");
//
// Create an InputStream of the file to be uploaded
//
String filename = "sample.zip";
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}

SFTP connection throws odd FileTransferException that exposes SFTP password

It is really bizarre, why would zehon return my location of my eclipse, and my SFTP password as part of a FileSystemException?
I have checked that the remote host is indeed a SFTP server, and the client is connecting using SFTP.
Zehon API here
Stacktrace
Reading file from C:\srcFolde\FileToBeUploaded.zip
com.zehon.exception.FileTransferException:
org.apache.commons.vfs.FileSystemException:
Unknown message with code:
"C:<location of eclipse>/<sftp password>?" does not exist
at int result = sftp.sendFile(filePath, ftpDestFolder);
Code
SFTPClient sftp = new SFTPClient(ftpServer, 22, ftpUserName, ftpPassword, true);
FileInputStream fis = null;
try {
fis = new FileInputStream(fileName);
String filePath=fileName.substring(0, fileName.length()-4) + ".zip";
String ftpDestFolder="\\sftpDestFolder";
int result = sftp.sendFile(filePath, ftpDestFolder);
Logger.debug("sftp result = " + result);
} catch (FileTransferException e) {
e.printStackTrace();
return false;
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
You've used the wrong constructor. From the Javadocs
http://www.zehon.com/javadocs/com/zehon/sftp/SFTPClient.html
You've passed ftpPassword where it's expecting privateKeyPath.

Java - Storing File on FTP Server fails

I am trying to store a byteArrayInputStream as File on a FTP Server. I could already connect to the Server and change the working path, but triggering the method to store the Stream as File on the Server returns always false.
I am using the apache FTPClient.
Can someone please give me a hint where my mistake can be!?
Here the Code:
String filename = "xyz.xml"
// connection returns true
connectToFtpServer(ftpHost, ftpUser, ftpPassword, exportDirectory);
// byteArray is not void
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
try {
// change returns true
result = ftpClient.changeWorkingDirectory(exportDirectory);
// storing the file returns false
result = ftpClient.storeFile(filename, byteArrayInputStream);
byteArrayInputStream.close();
ftpClient.logout();
} catch (...) {
...
} finally {
// disconnect returns true
disconnectFromFtpServer();
}
I don't believe it's your code. Here is another example that looks very similar from kodejava:
package org.kodejava.example.commons.net;
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;
public class FileUploadDemo {
public static void main(String[] args) {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("ftp.domain.com");
client.login("admin", "secret");
//
// Create an InputStream of the file to be uploaded
//
String filename = "Touch.dat";
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I agree it's file permissions. There is not a way to change permissions in java itself yet, but there are other solutions. See this thread: How do i programmatically change file permissions?
HTH,
James
It was actually a permission issue due to an invalid usergroup. After adding my user to the usergroup, i was able to store again files.

How to upload to FTP server in Java?

I have the following method to upload_files to an FTP server, I am not receiving any errors yet the file is not appearing on the server after its run. What could be the problem?
public static void upload_files(String un, String pw, String ip, String dir, String fn){
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect(ip);
client.login(un, pw);
String filename = dir+"/"+fn;
fis = new FileInputStream(filename);
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
System.out.println("uploaded");
} catch (IOException e) {
e.printStackTrace();
}
}
}
There are a number of possible issues. Assumption is that you are using FTPClient 3.x from Apache commons-net. If using something else, you should probably indicate that in your question. Ideas:
Check the reply status of the connection to make sure you are connecting as expected. There's an example on how to do this in the JavaDoc.
Your filename variable is the path to the local file you want to send. Is that really the same path you want to use for storing the file on the server (relative to the FTP login root)? It might be, but usually isn't. If not, your first parameter to client.storeFile(...) needs to be changed.
Most FTP servers provide ability to log all actions. Are you able to access yours? If so, that usually quickly makes clear what is going wrong.

File download in httpclient using java?

My code is,
import java.io.*;
import java.net.*;
public class DownloadHttp
{
public static void main(String a[])
{
DownloadHttp d = new DownloadHttp();
String addr = "http://www.gmail.com";
String file = "D:/venkatesh/Software/download1.html";
d.download(addr,file);
}
public void download(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
// Get the URL
URL url = new URL(address);
// Open an output stream to the destination file on our local filesystem
out = new BufferedOutputStream(new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
// Get the data
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
// Done! Just clean up and get out
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
// Shouldn't happen, maybe add some logging here if you are not
// fooling around ;)
}
}
}
}
Here I wants download specific file using httpClient using java.
It produces:
"java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)" as error.
How to resolve it, help me, thanks in advance.
I believe it is a network problem. Have you tried to access the url directly or are you behind a firewall?
Recompiled your code on my machine, it works perfectly well. I'm able to fetch files from the web.
Check if your web-browser can download the file for you (make sure it's not a network problem)
One thing to notice though, in your finally block you might want to close the streams separately. So if anything goes wrong with the input stream, the output stream will still be closed.
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ignored) {}
try {
if (out != null) {
out.close();
}
} catch (Exception ignored) {}
}
I think you are using a proxy when connecting to internet.
Set these in the code and then retry.
System.setProperty("http.proxyHost", *Proxy-IP*);
System.setProperty("http.proxyPort", *Proxy-Port*);

Categories

Resources