Java connection to FTP server instance code

  • 2020-04-01 04:29:38
  • OfStack

Without further ado, I will post the Java code directly to you.


 import java.io.IOException;
import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;
public class MyFtp {
static FtpClient myFtp;
static String hostname;
static String username;
static String password;

public static void main(String[] args) {
try {
hostname = "203.171.236.123";
myFtp = new FtpClient(hostname);
myFtp.login("user", "pass");
myFtp.binary();
showFileContents();
} catch (IOException e1) {
System.out.print(e1);
}
}
public static void showFileContents() {
int ch;
StringBuffer buf = new StringBuffer();
try {
TelnetInputStream inStream = myFtp.list();
while ((ch = inStream.read()) >= 0) {
buf.append((char) ch);
}
System.out.print(new String(buf.toString().getBytes("iso-8859-1"),
"GBK"));
inStream.close();
myFtp.closeServer();
} catch (Exception e) {
System.out.println("Error" + e);
}
}
}
[@more@]

The following are some of the control commands provided by the FtpClient class.

Public void CD (String remoteDirectory)

This command is used to switch the directory on the remote system to the directory specified by the parameter remoteDirectory.
Public void cdUp() : this command is used to switch the directory on the remote system to a higher directory.
Public String PWD () : this command displays the directory status on the remote system.
Public void binary() : this command sets the transport format to binary format.
Public void ASCII () : this command sets the transport protocol to ASCII format.
Public void rename(String String, String string1)

This command renames a directory or file on a remote system.
In addition to the above methods, the FtpClient class provides several methods that can be used to pass and retrieve directory listings and files. These methods return input and output streams that can be read or written. Here are some of the main methods.

Public TelnetInputStream list ()

Returns the input stream corresponding to the current directory on the remote machine.

Public TelnetInputStream get (String filename)

Gets the filename of the file on the remote machine and transfers it locally with a TelnetInputStream.

Public TelnetOutputStream put (String filename)

Opens an output stream as a write through which the file filename is passed to a remote computer.


Related articles: