This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have David & Dawn Griffiths on-line!
See this thread for details.
Win a copy of Head First Android this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

How to upload file to ftp in java

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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();
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Maybe calling:

netOut.flush();

before closing netOut will help.
 
Pratik Gupta
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.......
 
Rancher
Posts: 43027
76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How is that different from uploading any other kind of file? Make sure you set the transfer type to binary.
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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());
}
}
}
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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);

}
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic