I wrote a small ftp code to connect to a ftp server. The code
is able to construct FTP URL but fails to open the connection.
Any reason(s) for failure? Would appreciate help!
Code:
Code:
import java.lang.*;
import java.net.*;
import java.io.*;
public class ftp_test {
InetAddress address;
URL ftpurl;
InputStream in;
URLConnection ftpconnection;
public ftp_test (String hostname, String userid, String password) {
try {
address = InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
System.out.println("getByName failed: " + e);
System.exit(-1);
}
try {
String urlstring = new String();
urlstring += "ftp://" + userid + "@" + hostname;
System.out.println("FTP url string " + urlstring);
ftpurl = new URL(urlstring);
System.out.println("FTP URL is: " + ftpurl);
} catch (MalformedURLException e) {
System.out.println("ftpurl failed: " + e);
System.exit(-1);
}
/* open connection to url */
try {
ftpconnection = ftpurl.openConnection();
System.out.println("Opened url connecction");
} catch (IOException e) {
System.out.println("Connection open failed: " + e);
System.exit(-1);
}
}
static public void main (String[] args) {
if (args.length < 3 ) {
System.out.println("Usage: ftp_test <host> <userid> <password>");
System.exit(0);
}
new ftp_test(args[0], args[1], args[2]);
}
}
Run test:
java junk@mydom myname mypwd
Output:
FTP url string
ftp://[email protected] ftp url construction successful
FTP URL is:
ftp://[email protected] Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1525)
at sun.net.www.protocol.ftp.FtpURLConnection.<init>(FtpURLConnection.java:67)
at sun.net.www.protocol.ftp.Handler.openConnection(Handler.java:52)
at java.net.URL.openConnection(URL.java:781)
at ftp_test.<init>(ftp_test.java:35)
at ftp_test.main(ftp_test.java:68)