/** Request a directory listing from the server. */ public void dir() { String userInput; BufferedReader srvIn; Socket srv = null; /* Setup the appropriate sockets */ setupTransferMode(); out.println(commands[LIST]); System.out.println("=> LIST"); System.out.println(getResponse()); try { /* Setup the proper input streams based on the transfer mode */ if (passive) { srvIn = pasvIn; } else { srv = activeSock.accept(); srvIn = new BufferedReader(new InputStreamReader(srv.getInputStream())); } /* Display the directory listing */ while ((userInput = srvIn.readLine()) != null) { System.out.println(userInput); } srvIn.close(); if (srv != null) { srv.close(); } } catch (IOException e) { System.err.println("Error recieving data from server: " + e.getMessage()); } /* Clean up */ closeTransferMode(); System.out.println(getResponse()); }
/** * Request a specified file from the server. * * @param path The path to the file to acquire */ public void get(String path) { String userInput, resp; BufferedReader srvIn; InputStream inStr; Socket srv = null; /* Initialize the appropriate transfer mode */ setupTransferMode(); /* Request the file */ System.out.println("=> RETR " + path); out.println("RETR " + path); /* Spit out the response */ resp = getResponse(); System.out.println(resp); /* Validate response */ if (!resp.startsWith("150")) { debug("Invalid response from RETR command; aborting transfer"); closeTransferMode(); return; } try { /* Point to the appropriate input streams based on transfer mode */ if (passive) { srvIn = pasvIn; inStr = pasvSock.getInputStream(); } else { srv = activeSock.accept(); inStr = srv.getInputStream(); } /* ASCII transfer */ if (ascii) { FileWriter outFile = new FileWriter(new File(path).getName()); srvIn = new BufferedReader(new InputStreamReader(inStr)); while ((userInput = srvIn.readLine()) != null) { outFile.write(userInput + line_sep); } outFile.close(); srvIn.close(); } else { /* Binary transfer */ int bytesRead = 0; byte[] buf = new byte[512]; FileOutputStream outFile = new FileOutputStream(new File(path).getName()); BufferedInputStream binIn = new BufferedInputStream(inStr); while ((bytesRead = binIn.read(buf, 0, 512)) != -1) { outFile.write(buf, 0, bytesRead); } outFile.close(); binIn.close(); } if (srv != null) { srv.close(); } } catch (IOException e) { System.err.println("Error acquiring file: " + e.getMessage()); } /* Clean up */ closeTransferMode(); System.out.println(getResponse()); }