Here is my simple code:
public boolean sendCSV() throws IOException {
System.out.println("Translating from xls to csv...");
File xls = new File("file.xls");
File csvFile;
csvFile = CSVManager.xlsToCsv(xls);
csvFile.renameTo(new File("file.csv"));
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
System.out.println("Establishing connection...");
client.connect(ftpHost, ftpPort);
System.out.print(client.getReplyString());
System.out.println("Connection ok.");
if (client.login(ftpUser, ftpPass)) {
System.out.println("Login ok");
System.out.print(client.getReplyString());
System.out.println("Setting PASV");
client.enterLocalPassiveMode();
System.out.print(client.getReplyString());
if (client.changeWorkingDirectory("/MYDIR")) {
System.out.println("Dir changed");
System.out.print(client.getReplyString());
} else {
System.out.println("Error changing dir");
System.out.print(client.getReplyString());
}
String filename = csvFile.getName();
TrayIconManager.SwitchTrayToFull();
fis = new FileInputStream(filename);
if (client.storeFile(filename, fis)) {
System.out.println("File sent");
System.out.print(client.getReplyString());
} else {
System.out.println("Error during sending file");
System.out.print(client.getReplyString());
}
}
if (client.logout()) {
System.out.println("Logout ok");
System.out.print(client.getReplyString());
return true;
} else {
System.out.println("Logout problem");
System.out.print(client.getReplyString());
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What is the problem? The output says that
File sent
226-29 Kbytes used (0%) - authorized: 512000 Kb
226-File successfully transferred
226 0.343 seconds (measured here), 30.59 Kbytes per second
but is not true, because once I check on the ftp server the file is not there!
Why Kbytes used is 0%? Maybe is that the error?
The code seems to be ok, also the output.
So what is the real problem?
Related
Good day. I have imported org.apache.commons.net.ftp.FTP to my project and I faced some issues when upload the zip file to FTP.
When it uploads small file(<100MB), it works fine. But when it comes to larger file (>500MB), it will stops there, without returning and execute the remaining operation, even it the file is transferred to the server.
And how the function / FTP acknowledge when the transfer is done? Is there anyway to check it?
public class zipFTP
{
public boolean uploadFile(String ht, String usr, String ps, String fpath, String uploadloc)
{
FTPClient client = new FTPClient();
FileInputStream fis = null;
writeLog nLog = new writeLog();
String channel = "FTP";
boolean completed = false;
//client.setBufferSize(1048576);
client.setControlKeepAliveReplyTimeout(300);
//System.out.println(client.getBufferSize());
try
{
nLog.writeToLog(dumptoFTP.filename, channel, "Uploading...");
client.connect(ht);
client.login(usr, ps);
client.enterLocalPassiveMode();
client.setFileType(FTP.BINARY_FILE_TYPE);
fis = new FileInputStream(fpath);
completed = client.storeFile(uploadloc, fis);
//client.completePendingCommand(); //to complete the transaction entirely
if(completed)
{
if (dumptoFTP.isSysLog)
System.out.println("File uploaded");
nLog.writeToLog(dumptoFTP.filename, channel, "File uploaded");
}
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
if (dumptoFTP.isSysLog)
System.out.println("Upload failed");
nLog.writeToLog(dumptoFTP.filename, channel, "Upload failed");
nLog.writeToLog(dumptoFTP.filename, channel, e.toString());
}
finally
{
try
{
if(client.isConnected())
{
client.logout();
client.disconnect();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return completed;
}
}
Ended up, setBufferSize() does the trick
When i try to list files from my location using ftpClient.listFiles("folder"); it shows
org.eclipse.debug.core.DebugException: com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array.
Can some one guide me what i am doing wrong.
I use apache-commons-net-3.3
My code is
FTPClientConfig ftpClientConfig = new FTPClientConfig(FTPClientConfig.SYST_NT);
FTPClient ftpClient = new FTPClient();
ftpClient.configure(ftpClientConfig);
ftpClient.connect(hostName, Integer.valueOf(portNumber));
ftpClient.enterLocalPassiveMode();
ftpClient.login(username, password);
// Error throws here
FTPFile[] files = ftpClient.listFiles("folder");
This Exception is thrown when a user gave a Wrong or Encrypted Username Or Password.
Apache is not throwing the correct exception.
public void ConnectToFtp(String serverAdd,String username,String password){
try {
ftpclient.connect(serverAdd);
boolean login = ftpclient.login(username,password);
reply = ftpclient.getReplyCode();
if(FTPReply.isPositiveCompletion(reply)){
System.out.println("Connected Success");
}else {
System.out.println("Connection Failed");
ftpclient.disconnect();
}
if (login) {
System.out.println("Connection established...");
FTPFile[] ftpFiles = ftpclient.listFiles();
for (FTPFile ftpFile : ftpFiles) {
if (ftpFile.getType() == FTPFile.DIRECTORY_TYPE) {
System.out.printf("FTPFile: %s; %s%n",
ftpFile.getName(),
FileUtils.byteCountToDisplaySize(ftpFile.getSize()));
}
}
}
boolean logout = ftpclient.logout();
if (logout) {
System.out.println("Connection close...");
} else {
System.out.println("Connection fail...");
}
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
ftpclient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
I have created a simple client-server java socket app that can transfer a single file from client into the server through socket. What do I need to modify in my application so that I can send multiple files in a directory to the server?
this my simple client:
public void connect() {
while (!isConnected) {
try {
socket = new Socket("10.110.190.82", 7999);
outputStream = new ObjectOutputStream(socket.getOutputStream());
isConnected = true;
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error. Server is not running\n '"+e.getMessage()+"' "+
"\nThis Client will now close.", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
}
public void sendFile(String sourceFilePath, String fileName) {
if(socket.isConnected()){
while (socket.isConnected()) {
fileEvent = new FileEvent_1();
String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
fileEvent.setDestinationDirectory(destinationPath);
fileEvent.setFilename(fileName);
fileEvent.setSourceDirectory(sourceFilePath);
File file = new File(sourceFilePath);
if (file.isFile()) {
try {
DataInputStream diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
fileBytes.length - read)) >= 0) {
read = read + numRead;
}
fileEvent.setFileSize(len);
fileEvent.setFileData(fileBytes);
fileEvent.setStatus("Success");
} catch (Exception e) {
e.printStackTrace();
fileEvent.setStatus("Error");
}
} else {
System.out.println("path specified is not pointing to a file");
fileEvent.setStatus("Error");
}
try {
outputStream.writeObject(fileEvent);
System.out.println("Done...Going to exit");
JOptionPane.showMessageDialog(null, "Upload Success", "Success", JOptionPane.INFORMATION_MESSAGE);
Thread.sleep(3000);
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
} catch(InterruptedException ex){
ex.printStackTrace();
}
}
} else {
JOptionPane.showMessageDialog(null, "Socket is not connected", "FAILED", JOptionPane.ERROR_MESSAGE);
}
}
and this is my simple server, it contains a client handler and a server..
this is client_handler:
public class ClientHandler implements Runnable {
Socket socket;
PrintStream out;
private ObjectInputStream inputStream;
private FileEvent_1 fileEvent;
private File dstFile;
private FileOutputStream fileOutputStream;
ClientHandler(Socket s) {
socket = s;
}
#Override
public void run() {
try {
out = new PrintStream(socket.getOutputStream());
inputStream = new ObjectInputStream(socket.getInputStream());
downloadFile();
} catch (IOException e) {
System.out.println("PrintStream Error");
}
out.println("Hello!! I'm in!!!");
try {
socket.close();
} catch (IOException e) {
System.out.println("Failed to close, oddly...");
}
}
public void downloadFile() {
try {
fileEvent = (FileEvent_1) inputStream.readObject();
if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
System.out.println("Error occurred ..So exiting");
System.exit(0);
}
String outputFile = fileEvent.getDestinationDirectory() + fileEvent.getFilename();
if (!new File(fileEvent.getDestinationDirectory()).exists()) {
new File(fileEvent.getDestinationDirectory()).mkdirs();
}
dstFile = new File(outputFile);
fileOutputStream = new FileOutputStream(dstFile);
fileOutputStream.write(fileEvent.getFileData());
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("Output file : " + outputFile + " is successfully saved ");
Thread.sleep(000);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}}
and the server:
public static void main(String[] args) {
try {
socket = new ServerSocket(port);
System.out.println("SERVER START");
System.out.println("Bound to port: " + port);
} catch (IOException e) {
System.out.println("Cannot bind to port: " + port);
System.exit(0);
}
while (true) {
try {
Socket s = socket.accept();
System.out.println("New Client: "+s.getInetAddress().toString());
(new Thread(new ClientHandler(s))).start();
} catch (IOException e) {
System.out.println("Failed to accept client");
}
}
}
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
So you get the directory listing (list of all files in the directory), loop through the resulting fList and send them one by one as you would with a single file:
for(File file : fList) {
//file sending stuff
}
You can use JFileChooser if you want see the list of directories and list of files. for example:
JFileChooser jFilechooser1= new JFileChooser(new File("."));
to select the file:
if (jFilechooser1.showOpenDialog(this)==JFileChooser.APPROVE_OPTION)
{
dstFile=jFilechooser1.getSelectedFile();
}
I am trying to Upload file like this
try {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString
FTPClient ftpClient = new FTPClient();
ftpClient.connect("xxx.xxx.xx.xx");
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
{
boolean status=ftpClient.login("username", "password");
Log.d(TAG, "login status=="+status);
status=ftpClient.changeWorkingDirectory("New directory");
Log.d(TAG, "changeWorkingDirectory status=="+status);
status=ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
Log.d(TAG, "setFileType status=="+status);
ftpClient.enterLocalPassiveMode();
String srcFilePath=extStorageDirectory + "/AA.txt";
FileInputStream srcFileStream = new FileInputStream(new File(srcFilePath));
status=ftpClient.storeFile("AA.txt", srcFileStream);
Log.d(TAG, "upload status=="+status);
ftpClient.logout();
ftpClient.disconnect();
}
else
{
Log.d(TAG, "connectfail");
}
} catch (SocketException e) {
Log.d(TAG, "SocketException status=="+e.toString());
e.printStackTrace();
} catch (FileNotFoundException e) {
Log.d(TAG, "FileNotFoundException status=="+e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "IOException status=="+e.toString());
e.printStackTrace();
}
below is my logcat status
07-11 12:24:43.359: D/FTPDownloadDroid(10647): <!>com.ss.dr 138<!> login status==true
07-11 12:24:48.379: D/FTPDownloadDroid(10647): <!>com.ss.dr 141<!> changeWorkingDirectory status==true
07-11 12:24:48.859: D/FTPDownloadDroid(10647): <!>com.ss.dr 143<!> setFileType status==tr
07-11 12:24:54.359: D/FTPDownloadDroid(10647): <!>com.ss.dr 150<!> upload status==false
I want to Upload file on "New Directory" folder and file name AA.txt ** but it is giving Upload status false.**
Is the problem in server or in my Code???
Please help!!!!!!!!!
Thanks in advance
Try my code below, i used this to upload and download a song on the server. I am using the Apache's common lib.
Please make the changes for the directories and file name in the below code.
UPLOAD:
public void goforIt(){
FTPClient con = null;
try
{
con = new FTPClient();
con.connect("192.168.2.57");
if (con.login("Administrator", "KUjWbk"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/sdcard/vivekm4a.m4a";
FileInputStream in = new FileInputStream(new File(data));
boolean result = con.storeFile("/vivekm4a.m4a", in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
DOWNLOAD:
public void goforIt(){
FTPClient con = null;
try
{
con = new FTPClient();
con.connect("192.168.2.57");
if (con.login("Administrator", "KUjWbk"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/sdcard/vivekm4a.m4a";
OutputStream out = new FileOutputStream(new File(data));
boolean result = con.retrieveFile("vivekm4a.m4a", out);
out.close();
if (result) Log.v("download result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
Log.v("download result","failed");
e.printStackTrace();
}
}
Following is my java function to write a csv file in ftp location.The file gets created to ftp location but the file size is 0 bytes and file is empty.Kindly help as I am stuck
public int WriteFileToFtp(String FileName, String FileData) {
//get these details for the version??
//??
FTPClient ftp= new FTPClient();
try {
InputStream is = new ByteArrayInputStream(FileData.getBytes("ISO-8859-1"));
ftp.connect(ftpIP);
boolean isConnection = ftp.login(userName,password);
if(!isConnection){
logger.error("Connection failed");
return -1;
}
ftp.enterLocalActiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);//setting fileType
//?? go to directory using the circle code
if(ftpDirectoryToBeUpdate!=null && ftpDirectoryToBeUpdate.trim().length()>0)
{
logger.error("Changing directory for write="+ftpDirectoryToBeUpdate+" lcd="+ftp.printWorkingDirectory());
ftp.changeWorkingDirectory(ftpDirectoryToBeUpdate);
logger.error("Changed directory for write="+ftpDirectoryToBeUpdate+" lcd="+ftp.printWorkingDirectory());
}else
{
logger.error("Changed directory for write failed lcd="+ftp.printWorkingDirectory());
logger.error("DirectoryToReadFrom="+ftpDirectoryToBeUpdate);
}
ftp.storeFile(FileName,is) ;
logger.error(ftp.getReplyString());
is.close();
if(ftp.isConnected())
ftp.disconnect();
} catch (SocketException e) {
//logger.error(LoggerKeyWord.ERROR_ALERT + " FTP WRITE ERROR");
logger.error(e,e);
e.printStackTrace();
return -1;
} catch (IOException e) {
// logger.error(LoggerKeyWord.ERROR_ALERT + " FTP WRITE ERROR");
logger.error(e,e);
e.printStackTrace();
return -1;
}
try {
if(ftp.isConnected())
ftp.disconnect();
} catch (IOException e) {
logger.error (e,e);
e.printStackTrace();
return -1;
}
return 1;
}
have you tried closing input stream before saving the file?