The moose likes I/O and Streams and the fly likes How to upload file to ftp in java Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of Practical Unit Testing with TestNG and Mockito this week in the Testing forum!
JavaRanch » Java Forums » Java » I/O and Streams
Reply Bookmark "How to upload file to ftp in java" Watch "How to upload file to ftp in java" New topic
Author

How to upload file to ftp in java

Pratik Gupta
Greenhorn

Joined: May 31, 2007
Posts: 2
Please help me out....
I want to upload a file to ftp using my java program.
I got this bit of code but its not working....
The file is uploaded to the ftp server but its size is always 0 bytes...
What might be the problem???
Code-
String server="www.test.com";
String userName="test";
String pw="test";
String fileName = "test.dat";
FtpClient ftpClient = new FtpClient();
try {
ftpClient.openServer(server);
ftpClient.login(userName, pw);
ftpClient.cd("myfolder/test/");
ftpClient.binary();
TelnetOutputStream netOut = ftpClient.put(fileName);
File file = new File(fileName);
// Now transfer the file contents
ObjectInputStream fileIn = new ObjectInputStream(new FileInputStream(file));
byte c[]=new byte[1000];
int read = 0;
while ((read = fileIn.read(c)) != -1) {
netOut.write(c, 0, read);
}
fileIn.close();
netOut.close();
ftpClient.closeServer();
Jesper de Jong
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 11634

Maybe calling:

netOut.flush();

before closing netOut will help.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Pratik Gupta
Greenhorn

Joined: May 31, 2007
Posts: 2
Hey i have got one more problem....
I want to uplaod a file containing a Key object...i.e. I created the file by using
KeyPairGenerator keypair=new KeyPairGenerator();
Key key=keypair.getPrivate();
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("public.dat");
out.writeObject(key);


Now i want to upload this file to a ftp server....
Plaese help me out on this.......
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 32765
How is that different from uploading any other kind of file? Make sure you set the transfer type to binary.


Android appsImageJ pluginsJava web charts
vinay varanasi
Greenhorn

Joined: Apr 29, 2004
Posts: 10
Hey
I have been using the followinf code to ftp my files for the past 4 months and it has been working fine.

The ftp works fine as long as the band width is high enough based on the file size.

I have also put a success check based on the file size.

You can use the putFile(<file name> method to initiate FTP.


See if the following code helps.
==========================================================================
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.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.StringTokenizer;
import java.util.*;
import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;
import sun.net.www.protocol.http.HttpURLConnection;
import sun.security.x509.IssuerAlternativeNameExtension;
import java.io.*;

public class FtpToServer extends FtpClient
{
public static int BUFFER_SIZE = 10240;
private static FtpClient m_client;
private static String host = "";
private static String user = "";
private static String password = "";
private static String targetDataDir = "";
private static String targetResultsDir = "";
private static String sourceDir = "";
private static String sourceFile = "";
public static char SEPARATOR = '/';
public String targetFile = "";
public String ftpStartTime="";
public String ftpEndTime="";
public String servletStartTime="";
public String servletEndTime="";



private String getUniqueId()
{
String strUniqueId = "";
Date date = new Date();
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMddhhmmssSSSSSS");
strUniqueId = simpledateformat.format(date)+(int)(Math.ceil(Math.random()*1000));
return strUniqueId;
}

public String getCurrentDateTime()
{
Date date = new Date();
SimpleDateFormat simpledateformat = new SimpleDateFormat("hhmmssSSSSSS");
String datetime = simpledateformat.format(date);
datetime = datetime.substring(0,2)+":"+datetime.substring(2,4)+":"+datetime.substring(4,6)+"."+datetime.substring(6);
return datetime;
}

private String getUniqueFolderId()
{
String strUniueId = getUniqueId();
String strDateId = "";
String strTimeId = "";
String strFolderId = null;
strDateId = strUniueId.substring(0,7) + SEPARATOR;
strTimeId = strUniueId.substring(8,9) + SEPARATOR;
strFolderId = strDateId + strTimeId + strUniueId ;
return strFolderId;
}

public FtpToServer(StringBuffer dCSVFile,StringBuffer rCSVFIle) throws IOException
{
//Properties p = new Properties();
//p.load(new FileInputStream("ScrutiNet.properties"));
host=ScrutinetConstants.TARGETMACHINE;
user=ScrutinetConstants.USER;
password=ScrutinetConstants.PASSWORD;
targetDataDir=ScrutinetConstants.TARGETROOTDIRECTORYDATA;
targetResultsDir=ScrutinetConstants.TARGETROOTDIRECTORYRESULTS;
ftpStartTime = getCurrentDateTime();
//System.out.println(host);
m_client = new FtpClient(host,21);
//System.out.println(user + " " + password);
m_client.login(user, password);
//System.out.println("User " + usder + " login OK");
//System.out.println("hello " + m_client.welcomeMsg);
//System.out.println("Calling Ftp of Data CSV");
m_client.cd(targetDataDir);
m_client.binary();
//System.out.println("Calling first put CSV");
putFile(dCSVFile);
//System.out.println("After Calling first put CSV");


//System.out.println("Calling Ftp of Results CSV");
m_client.cd(targetResultsDir);
putFile(rCSVFIle);
ftpEndTime = getCurrentDateTime();
}

protected void disconnect()
{
if (m_client != null)
{
try
{
m_client.closeServer();
}
catch (IOException ex)
{
ex.printStackTrace();
}
m_client = null;
}
}

protected void putFile(StringBuffer sbFileNameToSend)
{
if (sourceFile.length() == 0)
{
//System.out.println("Please enter file name");
}
byte[] buffer = new byte[BUFFER_SIZE];
try
{
File f = new File(sbFileNameToSend.toString());
int size = (int) f.length();
//System.out.println("Entering FTP");
FileInputStream in = new FileInputStream(sbFileNameToSend.toString());
OutputStream out = m_client.put(sbFileNameToSend.substring(sbFileNameToSend.lastIndexOf("\\")+1));
int counter = 0;
while (true)
{
int bytes = in.read(buffer);
if (bytes < 0) break;
out.write(buffer, 0, bytes);
counter += bytes;
}
System.out.println("FTP Done");
out.close();
in.close();
}
catch (Exception ex)
{
ex.printStackTrace();
System.out.println("Error in FTP: " + ex.toString());
}
}
}


Vinay V
Vishnu Suresh
Greenhorn

Joined: Feb 08, 2012
Posts: 1
TelnetOutputStream netOut = ftpClient.put(fileName);
File file = new File(fileName);
ObjectInputStream fileIn = new ObjectInputStream(new FileInputStream(file));
byte c[]=new byte[1000];
int read = 0;
while ((read = fileIn.read(c)) != -1) {
netOut.write(c, 0, read);
}

I made some modification to the following lines of this code snippet and found to have uploaded the file successfully....

TelnetOutputStream netOut = ftpClient.put(fileName);
File file = new File(fileName);
ObjectInputStream fileIn = new ObjectInputStream(new FileInputStream(file));
int read = 0;
while ((read = fileIn.read()) != -1) {
netOut.write(read);

}
 
 
subject: How to upload file to ftp in java
 
Threads others viewed
FTP very slow
Reading log files from various unix servers through Java program on windows
Multithreading in Quartz Scheduler
How to Change the File Name for Each Uploaded Files to the Socket Server?
FTP in Java
IntelliJ Java IDE