Ola.. Eu achei um exemplo na rede de FTP... Essa classe abre a conexao com o servidor e faz upload de um arquivo de cada vez...
Espero que isso lhe ajude... Um abraco, Janaine Javaneando wrote: > Oi, > > preciso urgente de uma classe de exemplo (fazFTP) > que abre uma conexao ftp com um site qualquer, > informa usuario e senha, lista os arquivos do > servidor, muda o diretorio, faz um get e um > delete! > > Será que eu vou ter que usar sockets para > fazer isto? > > Não existe algo tipo java.net.ftpconnection não? > > Se alguém me mandar um exemplo eu agradeço. > > Brigadao > > > > >_______________________________________________________________________________________________ > Yahoo! GeoCities > Tenha seu lugar na Web. Construa hoje mesmo sua home page no Yahoo! GeoCities. É >fácil e grátis! > http://br.geocities.yahoo.com/ > > ------------------------------ LISTA SOUJAVA ---------------------------- > http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP > dúvidas mais comuns: http://www.soujava.org.br/faq.htm > regras da lista: http://www.soujava.org.br/regras.htm > para sair da lista: envie email para [EMAIL PROTECTED] > -------------------------------------------------------------------------
// // **************************** Security Warning! ************************ // This is a serious warning, and you need to pay attention to it. // // To work, this program needs you to put your ftp password into the // code as a String. This is only appropriate on an Intranet or when // the applet is on a page to which access is otherwise controlled. // // A malicious person could access the applet class file and easily // retrieve YOUR password. Then they would have access to your ftp // account. They could add, delete, or change files. They could even // change the password. That would be very bad for you. // // Giving away your password is frequently not allowed by the terms of // your account provider. Do NOT use this program unless you are // authorized to pass on your ftp password, and you are able to firewall // the ftp account or otherwise protect against intrusion. One thing // you could do is have a very small ftp area, and only allow existing // files to be appended (for example). // // Creating an applet with this program is like publishing your password // to anyone who can access the applet class file. // // If you still want to proceed, it is at your own risk. // **************************** Security Warning! ************************ // // Usage: // // to upload a file: // MyFTP ftp = new MyFTP( <servername>, <user>, <password> ); // ftp.upload( <directory>, <filename>, <contents of file> ); // // to download a file: // MyFTP ftp = new MyFTP( <servername>, <user>, <password> ); // String contents = ftp.download( <directory>, <filename> ); // // the default is ASCII transfer, an overloaded method does bin. // ////////////////////////////////////////////////////////////////////////// // NOTE: This code was adapted from the LinLyn class available at // http://www.afu.com. I added overloaded methods for buffered file i/o. // See the main method for examples. RMK ///////////////////////////////////////////////////////////////////////// import java.io.*; import java.net.*; import java.util.*; public class MyFTP { // FOR INITIAL DEBUGGING: set the variable to "true" private boolean DEBUG = true; private static final int CNTRL_PORT = 21; private Socket csock = null; private Socket dsock = null; private DataInputStream dcis; private PrintStream pos; // constructor needs servername, username and passwd public MyFTP(String server, String user, String pass) { try { ftpConnect(server); ftpLogin(user, pass); } catch(IOException ioe) {ioe.printStackTrace();} } public String download(String dir, String file) throws IOException { return download(dir, file, true); } public String download(String dir, String file, boolean asc) throws IOException { ftpSetDir(dir); ftpSetTransferType(asc); dsock = ftpGetDataSock(); InputStream is = dsock.getInputStream(); ftpSendCmd("RETR "+file); String contents = getAsString(is); ftpLogout(); return contents; } // this is the buffered version public void download(String dir, String file, boolean asc, String dest) throws Exception { int BUFSIZE = 1000; byte[] buf = new byte[BUFSIZE]; int i; if (DEBUG) { System.out.println("Downloading " + file); } ftpSetDir(dir); ftpSetTransferType(asc); dsock = ftpGetDataSock(); BufferedInputStream in = new BufferedInputStream(dsock.getInputStream(), BUFSIZE); FileOutputStream out = new FileOutputStream(dest); ftpSendCmd("RETR "+file); while ((i = in.read(buf)) != -1) { out.write(buf, 0, i); out.flush(); } in.close(); out.close(); ftpLogout(); } private void ftpConnect(String server) throws IOException { // Set up socket, control streams, connect to ftp server // Open socket to server control port 21 csock = new Socket(server, CNTRL_PORT); // Open control streams InputStream cis = csock.getInputStream(); dcis = new DataInputStream(cis); OutputStream cos = csock.getOutputStream(); pos = new PrintStream(cos); // handle more than one line returned String reply = dcis.readLine(); String numerals = reply.substring(0, 3); String hyph_test = reply.substring(3, 4); String next = null; if(hyph_test.equals("-")) { boolean done = false; while(!done) { // read lines til find "" -> last line next = dcis.readLine(); if(next.substring(0,3).equals(numerals) && next.substring(3, 4).equals(" ")) done = true; } } if(numerals.substring(0,3).equals("220")) // ftp server alive ; // System.out.println("Connected to ftp server"); else System.err.println("Error connecting to ftp server."); } private Socket ftpGetDataSock() throws IOException { // Go to PASV mode, capture server reply, parse for socket setup // V2.1: generalized port parsing, allows more server variations String reply = ftpSendCmd("PASV"); // New technique: just find numbers before and after ","! StringTokenizer st = new StringTokenizer(reply, ","); String[] parts = new String[6]; // parts, incl. some garbage int i = 0; // put tokens into String array while(st.hasMoreElements()) { // stick pieces of host, port in String array try { parts[i] = st.nextToken(); i++; } catch(NoSuchElementException nope){nope.printStackTrace();} } // end getting parts of host, port // Get rid of everything before first "," except digits String[] diggies = new String[3]; for(int j = 0; j < 3; j++) { // Get 3 characters, inverse order, check if digit/character diggies[j] = parts[0].substring(parts[0].length() - (j + 1), parts[0].length() - j); // next: digit or character? if(!Character.isDigit(diggies[j].charAt(0))) diggies[j] = ""; } parts[0] = diggies[2] + diggies[1] + diggies[0]; // Get only the digits after the last "," String[] porties = new String[3]; for(int k = 0; k < 3; k++) { // Get 3 characters, in order, check if digit/character // May be less than 3 characters if((k + 1) <= parts[5].length()) porties[k] = parts[5].substring(k, k + 1); else porties[k] = "FOOBAR"; // definitely not a digit! // next: digit or character? if(!Character.isDigit(porties[k].charAt(0))) porties[k] = ""; } // Have to do this one in order, not inverse order parts[5] = porties[0] + porties[1] + porties[2]; // Get dotted quad IP number first String ip = parts[0]+"."+parts[1]+"."+parts[2]+"."+parts[3]; // Determine port int port = -1; try { // Get first part of port, shift by 8 bits. int big = Integer.parseInt(parts[4]) << 8; int small = Integer.parseInt(parts[5]); port = big + small; // port number } catch(NumberFormatException nfe) {nfe.printStackTrace();} if((ip != null) && (port != -1)) dsock = new Socket(ip, port); else throw new IOException(); return dsock; } private void ftpLogin(String user, String pass) throws IOException { ftpSendCmd("USER "+user); ftpSendCmd("PASS "+pass); } private void ftpLogout() {// logout, close streams try { if(DEBUG) System.out.println("sending BYE"); pos.print("BYE" + "\r\n" ); pos.flush(); pos.close(); dcis.close(); csock.close(); dsock.close(); } catch(IOException ioe) {ioe.printStackTrace();} } private String ftpSendCmd(String cmd) throws IOException { // This sends a dialog string to the server, returns reply // V2.0 Updated to parse multi-string responses a la RFC 959 // Prints out only last response string of the lot. pos.print(cmd + "\r\n" ); String reply = dcis.readLine(); String numerals = reply.substring(0, 3); String hyph_test = reply.substring(3, 4); String next = null; if(hyph_test.equals("-")) { boolean done = false; while(!done) { // read lines til find "" -> last line next = dcis.readLine(); if(next.substring(0,3).equals(numerals) && next.substring(3, 4).equals(" ")) done = true; } if(DEBUG) System.out.println("Response to: "+cmd+" was: "+next); return next; } else if(DEBUG) System.out.println("Response to: "+cmd+" was: "+reply); return reply; } private void ftpSetDir(String dir) throws IOException { // cwd to dir ftpSendCmd("CWD "+dir); } private void ftpSetTransferType(boolean asc) throws IOException { // set file transfer type String ftype = (asc? "A" : "I"); ftpSendCmd("TYPE "+ftype); } ///////////////// private fields //////////////////// private String getAsString(InputStream is) { int c=0; char lineBuffer[]=new char[128], buf[]=lineBuffer; int room= buf.length, offset=0; try { loop: while (true) { // read chars into a buffer which grows as needed switch (c = is.read() ) { case -1: break loop; default: if (--room < 0) { buf = new char[offset + 128]; room = buf.length - offset - 1; System.arraycopy(lineBuffer, 0, buf, 0, offset); lineBuffer = buf; } buf[offset++] = (char) c; break; } } } catch(IOException ioe) {ioe.printStackTrace();} if ((c == -1) && (offset == 0)) { return null; } return String.copyValueOf(buf, 0, offset); } // main method for testing purposes public static void main(String args[]) { MyFTP ftp; String host = "Enter ftp hostname here"; String username = "Enter username here"; String password = "Enter password here"; boolean ascii = true; boolean binary = false; try { // download one ascii file //ftp = new MyFTP(host, username, password); //ftp.download("", "index.html", ascii, "E:\\temp\\index.html"); // download one binary file //ftp = new MyFTP(host, username, password); //ftp.download("mcgraw-hill", "ch01.zip", binary, "E:\\temp\\ch01.zip"); // upload one ascii file //ftp = new MyFTP(host, username, password); //ftp.upload("", "test.html", new File("E:\\temp\\test.html"), ascii); // upload one binary file ftp = new MyFTP(host, username, password); ftp.upload("", "test.zip", new File("E:\\temp\\test.zip"), binary); } catch (Exception e) { e.printStackTrace(); } } // this is the buffered version used in the agent public void upload(String dir, String filename, File file, boolean asc) throws Exception { int BUFSIZE = 1000; byte[] buf = new byte[BUFSIZE]; ftpSetDir(dir); ftpSetTransferType(asc); dsock = ftpGetDataSock(); OutputStream os = dsock.getOutputStream(); BufferedOutputStream out = new BufferedOutputStream(os); FileInputStream in = new FileInputStream(file); ftpSendCmd("STOR "+filename); int i; while ((i = in.read(buf)) != -1) { out.write(buf, 0, i); out.flush(); } in.close(); out.close(); ftpLogout(); } public void upload(String dir, String file, String what) throws IOException { upload(dir, file, what, true); } public void upload(String dir, String file, String what, boolean asc) throws IOException { ftpSetDir(dir); ftpSetTransferType(asc); dsock = ftpGetDataSock(); OutputStream os = dsock.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); ftpSendCmd("STOR "+file); dos.writeBytes(what); dos.flush(); ftpLogout(); } }
------------------------------ LISTA SOUJAVA ---------------------------- http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm para sair da lista: envie email para [EMAIL PROTECTED] -------------------------------------------------------------------------