This program started out as a learning exercise on Sockets, but a co-worker asked if I could help her with a program that would copy a file from a secure ftp site down to our local server. The file is an Excel file. I have done
testing with the follwing code on a pdf, xls, and a gif. I get the same results, a butchered file. The pdf file was the best test because I could see the results easily in my Text Editor. Extra newlines appear.
Thank you again for looking at this, sorry about the code past I am not sure what to expect when I post this!
public class ProxyTest {
public static void main(
String argv[] ) {
Socket mySocket = null;
PrintWriter cmdout = null;
String theurl = "myftpsite";
String fileName = "test.xls";
String dirName = "tmp/";
String file = "d:\\my.xls";
try {
mySocket = new Socket(theurl, 21);
cmdout = new PrintWriter(new OutputStreamWriter(mySocket.getOutputStream()));
String tmp = mySocket.getInetAddress().toString();
if (mySocket == null)
throw new IOException ("The Socket never opened");
System.out.println("Address : " + tmp);
URL url = new URL("myftpsite");
URLConnection connection = url.openConnection();
cmdout.println("USER myusername");
cmdout.flush();
cmdout.println("PASS mypassword");
cmdout.flush();
cmdout.println("CWD " + dirName);
cmdout.flush();
ServerSocket server = new ServerSocket(0);
String addr = InetAddress.getLocalHost().getHostAddress();
addr = addr.replace('.', ',');
int port = server.getLocalPort();
int portHi = port / 256;
int portLo = port % 256;
addr += "," + portHi + "," + portLo;
cmdout.println("PORT " + addr);
cmdout.flush();
cmdout.println("RETR " + fileName);
cmdout.flush();
Socket client = server.accept();
BufferedInputStream in = new BufferedInputStream(client.getInputStream());
FileOutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024 * 8];
int bytesRead;
while (-1 != (bytesRead = in.read(buffer, 0, buffer.length))) {
out.write(buffer, 0, bytesRead);
System.out.println("byte : " + bytesRead);
}
in.close();
out.close();
client.close();
server.close();
} catch (UnknownHostException e) {
System.err.println("Don't know about host: myweb.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: ftp server.");
System.exit(1);
}
try {
mySocket.close();
} catch (IOException e) {
System.err.println("Can not close");
System.exit(1);
}
}
}