FTP in Java

I would like transfer files between machines using Java (a Java FTP). Is there a sample code available ? I understand that there are some api in the sun packages but am not able to find it. Please help
[222 byte] By [hpandit] at [2007-9-26 8:21:39]
# 1
You can download the FTP bean suite available at www.alphaworks.ibm.com. It's open-source.
ramani_ranjan at 2007-7-1 18:55:41 > top of Java-index,Core,Core APIs...
# 2
The API in the Sun packages is URL and URLConnection. Downloading files is straightforward, you just do openConnection and getInputStream. I'm not sure whether uploading is equally simple.
trejkaz at 2007-7-1 18:55:41 > top of Java-index,Core,Core APIs...
# 3

The code is below,u can remove excptions and put ur own exception.

import java.io.*;

import java.net.*;

import java.util.*;

import java.text.DateFormat;

public class FTPReader

{

public static final String POSITIVE_COMPLETE = new String("2");

public static final String NEGATIVE_PERMANENT = new String("5");

private HostDataConnection hdc;

private InetAddress remoteIP;

private StringBuffer log;

private BufferedInputStream bis;

private BufferedReader instream;

private DataOutputStream outstream;

public static final int FTPport = 21;

private String host = new String();

private String user = new String();

private String password = new String();

private String response = new String();

private String currentDir = new String();

private String responseCode = new String();

private Socket controlSocket ;

private int lastPort;

private boolean isConnected;

private boolean isLoggedIn;

private String fileString = new String();

private String fileName = new String();

private String path = new String();

private boolean flag = MobilContoResources.DISPLAY;

public String getPtlfFile(String fileName,String path,String hostName,String userName,String psw)throws MobilContoException

{

this.fileName = fileName;

this.path = path;

this.host = hostName;

this.user = userName;

this.password = psw;

connectControlConnection();

sendListRequest();

return this.fileString;

}

public static void main(String str[])

{

try

{

FTPReader tst = new FTPReader();

tst.host = str[0];

tst.user = str[1];

tst.password = str[2];

tst.fileName = str[3];

tst.path = str[4];

tst.connectControlConnection();

System.out.println("FILE FROM FTP ::\n"+tst.fileString);

}

catch(Exception ex)

{

ex.printStackTrace();

}

}

public void connectControlConnection()throws MobilContoException

{

log = new StringBuffer();

try

{

remoteIP = InetAddress.getByName(host);

controlSocket = new Socket(remoteIP, FTPport);

isConnected = true;

}

catch(UnknownHostException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("Unknown Host error in HostControlConnection:\nHost " + host + " not known");

}

catch(IOException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("IO error in HostControlConnection:\nCould not open control socket");

}

if(isConnected)

{

try

{

instream = new BufferedReader(new InputStreamReader(controlSocket.getInputStream()));

outstream = new DataOutputStream(controlSocket.getOutputStream());

logOn();

}

catch(IOException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("IO error in HostControlConnection:\nCould not open control streams");

}

}

}

public void logOn()throws MobilContoException

{

getControlConnectionResponse("");

sendControlConnectionRequest("USER " + user);

sendControlConnectionRequest("PASS " + password);

}

public void getControlConnectionResponse(String request)throws MobilContoException

{

String temp = new String();

responseCode = new String();

int i;

try

{

while((i = instream.read()) != 10)

{

temp = temp.concat(String.valueOf((char)i));

}

}

catch(IOException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("IO error in HostControlConnection:\nCould not read from control connection");

}

info(" ->"+temp + "\n");

testResponseCode(temp, request);

}

public void testResponseCode(String ressponse, String request)throws MobilContoException

{

responseCode = String.valueOf(ressponse.charAt(0));

if(ressponse.startsWith("230-"))

getControlConnectionResponse("");

if(responseCode.equals(NEGATIVE_PERMANENT) && request.startsWith("PASS"))

{

closeControlSocket();

throw new MobilContoException("Could not log in!");

}

if(ressponse.startsWith("230 User"))

isLoggedIn = true;

if(request.equals("PWD") && responseCode.equals(POSITIVE_COMPLETE))

{

String temp = new String();

for(int i = 5; i < ressponse.length() && ressponse.charAt(i) != '"'; i++)

{

char c = ressponse.charAt(i);

temp = temp.concat(String.valueOf(c));

}

currentDir = temp;

}

if(request.startsWith("RETR") &&ressponse.startsWith("550"))

{

throw new MobilContoException("FILE NOT FOUND EXCEPTION :"+ressponse);

}

}

public void sendListRequest()throws MobilContoException

{

StringBuffer stfb = new StringBuffer("");

sendControlConnectionRequest("PWD");

hdc = new HostDataConnection();

hdc.createDataConnection();

sendControlConnectionRequest("PORT " + hdc.getPortCommandString());

if(path != null && !path.equals(""))sendControlConnectionRequest("CWD "+path);

sendControlConnectionRequest("RETR "+fileName);

hdc.acceptDataConnectionLocally();

bis = hdc.streamFromRemote;

int carValue;

try

{

while((carValue = bis.read()) != -1)

{

stfb.append((char)carValue);

}

fileString = stfb.toString();

}

catch(IOException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("IO error in HostControlConnection:\nCould not read from control connection");

}

}

public void sendControlConnectionRequest(String request)throws MobilContoException

{

if(request.startsWith("PASS"))

{

String temp = new String();

for(int i = 0; i < password.length(); i++)

temp = temp.concat("*");

info(" ->PASS " + temp + "\n");

} else

{

info(" ->"+request + "\n");

}

try

{

outstream.writeBytes(request);

outstream.write(13);

outstream.write(10);

outstream.flush();

}

catch(IOException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("IO error in HostControlConnection:\nCould not send through control connection");

}

getControlConnectionResponse(request);

}

public void closeControlSocket()throws MobilContoException

{

isConnected = false;

isLoggedIn = false;

try

{

controlSocket.close();

}

catch(IOException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("IO error in HostControlConnection:\nCould not close control socket after login failure");

}

}

public void info(String message)

{

if(flag)System.out.println("<info><FTPReader>>>><<<<<"+message+">>>>>>>");

}

}

prem_kumar76 at 2007-7-1 18:55:41 > top of Java-index,Core,Core APIs...
# 4

import java.io.*;

import java.net.*;

public class HostDataConnection

{

public BufferedInputStream streamFromRemote;

public DataOutputStream streamToRemote;

public Socket dataLocalSocket;

public ServerSocket dataServerSocket;

public InetAddress inetAddress;

public String addressString;

public String localPortString;

public String portCommandString;

public int localPort;

public HostDataConnection()

{

}

public void acceptDataConnectionLocally()throws MobilContoException

{

try

{

dataLocalSocket = dataServerSocket.accept();

}

catch(IOException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("IO error in HostDataConnection:\nCould not accept connection locally");

}

try

{

streamFromRemote = new BufferedInputStream(dataLocalSocket.getInputStream());

}

catch(IOException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("IO error in HostDataConnection:\nCould not get the remote input stream");

}

try

{

streamToRemote = new DataOutputStream(dataLocalSocket.getOutputStream());

}

catch(IOException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("IO error in HostDataConnection:\nCould not get the remote output stream");

}

}

public void closeDataSockets()throws MobilContoException

{

try

{

dataServerSocket.close();

dataLocalSocket.close();

}

catch(IOException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("IO error in HostDataConnection:\nCould not close data socket");

}

}

public void createDataConnection()throws MobilContoException

{

try

{

dataServerSocket = new ServerSocket(0);

}

catch(IOException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("IO error in HostDataConnection:\nCould not create local connection");

}

try

{

localPort = dataServerSocket.getLocalPort();

inetAddress = dataServerSocket.getInetAddress();

inetAddress = InetAddress.getLocalHost();

addressString = inetAddress.getHostAddress();

localPortString = "," + ((localPort & 0xff00) >> 8) + "," + (localPort & 0xff);

}

catch(IOException _ex)

{

_ex.printStackTrace();

throw new MobilContoException("IO error in HostDataConnection:\nCould not get information about the local connection");

}

portCommandString = addressString.replace('.', ',') + localPortString;

}

public String getPortCommandString()

{

return portCommandString;

}

}

prem_kumar76 at 2007-7-1 18:55:41 > top of Java-index,Core,Core APIs...
# 5

In JDK 1.2.2 we need not to have all this ftp implementation classes.

The following code sample works in JDK 1.2.2

public void ftpReader(String username, String password, String hostName, String filename) {

System.err.println(System.getProperty("java.version");

try {

String hostStr = username + ":" + password + "@" + hostName;

URL url = new URL("ftp", hostStr, 21, filename);

InputStream stream = url.openStream();

BufferedReader in = new BufferedReader(new InputStreamReader(stream));

String line = in.readLine();

....

} catch(UnknownHostException e) { e.printStackTrace(); }

catch (IOException ioe) { ioe.printStackTrace(); }

}

}

But the same is not working in JVM 1.3.0

I've posted one query in this regard, you can review that for the detailed message. Here is the link to that post,

http://forum.java.sun.com/thread.jsp?forum=4&thread=175880

And, if you can provide any clue to this behaviour, that will be a big help,

thanks,

ajay

SharmaAJ at 2007-7-1 18:55:41 > top of Java-index,Core,Core APIs...
# 6

http://www.savarese.org/oro/software/NetComponents.html

try the classes at this link. They work well for me, I have a few different applets implementing the classes. The applets can upload files and graphics to the webserver.If you use a applet you have to grant it appropriate permissions with the policytool or sign the jar.

mochajavatea at 2007-7-1 18:55:41 > top of Java-index,Core,Core APIs...
# 7

JavaWorld published an article about this topic. It is called "Java FTP client libraries reviewed" and it can be found here :

http://www.javaworld.com/javaworld/jw-04-2003/jw-0404-ftp.html

Best regards

Jean-Pierre Norguet

--

Jean-Pierre Norguet

JavaWorld Press

http://wasa.ulb.ac.be/jp.html

norguet at 2007-7-1 18:55:41 > top of Java-index,Core,Core APIs...