Erreur de connexion

mimi1255 Messages postés 87 Date d'inscription mardi 22 janvier 2008 Statut Membre Dernière intervention 14 mars 2024 - 29 févr. 2008 à 13:46
mimi1255 Messages postés 87 Date d'inscription mardi 22 janvier 2008 Statut Membre Dernière intervention 14 mars 2024 - 3 mars 2008 à 21:14
Bonjour, j'ai crée un serveur ftp et j'essaye de me connecter dessus à partir d'un code en java, mais j'ai cette erreur:
java.io.FileNotFoundException: C:\Employes (Accès refusé)
        at java.io.FileOutputStream.open(Native Method)

voici mon code:

le 1er fichier:


package test;

import test.SunFtpWrapper;
import java.io.*;

public class FtpWrapperTest {
    public static void main (String[] args) {
        try {
            SunFtpWrapper ftp = new SunFtpWrapper();
            String serverName = "127.0.0.1";
            ftp.openServer(serverName);
            if (ftp.serverIsOpen()) {
                System.out.println("Connected to " + serverName);
                try {
                    ftp.login("DRH", "admin");
                    System.out.println("Welcome message:\n" + ftp.welcomeMsg);
                    System.out.println("Current Directory: " + ftp.pwd());
                    System.out.println("Results of a raw LIST command:\n" + ftp.listRaw());
                    System.out.println("Downloading file robots.txt");
                    ftp.ascii();
                    ftp.downloadFile("25.jpg", "C:\\Employes");
                } catch (Exception ftpe) {
                    ftpe.printStackTrace();
                } finally {
                    ftp.closeServer();
                }
            } else {
                System.out.println("Unable to connect to" + serverName);
            }
            System.out.println("Finished");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}



mon 2ème fichier:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package test;

import sun.net.ftp.FtpClient;
import java.util.Vector;
import java.io.*;

public class SunFtpWrapper extends FtpClient {
   
    
    /** Get the present working directory */
    public String pwd() throws IOException {
        issueCommand("PWD");
        if (isValidResponse()) {
            String response = getResponseString().substring(4).trim();
            if (response.startsWith("""))
                response = response.substring(1);
            if (response.endsWith("""))
                response = response.substring(0, response.length() - 1);
            return response;
        } else {
            return "";
        }
    }
    
    /** Go up one directory */
    public boolean cdup() throws IOException {
        issueCommand("CDUP");
        return isValidResponse();
    }
    
    /** Create a new directory */
    public boolean mkdir (String newDir) throws IOException {
        issueCommand("MKDIR " + newDir);
        return isValidResponse();
    }
    
    /** Delete a remote file */
    public boolean deleteFile (String fileName) throws IOException {
        issueCommand("DELE " + fileName);
        return isValidResponse();
    }
    
    /** Get the results of the LIST command as a Vector of Strings. 
      * Because there's no standard format for the results of a LIST
      * command, it's hard to tell what resulting data will look like.
      * Just be aware that different servers have different ways of
      * returning your LIST data. */
    public Vector listRaw() throws IOException {
        String fileName;
        Vector ftpList = new Vector();
        BufferedReader reader = new BufferedReader(new InputStreamReader(list()));
        while ((fileName = reader.readLine()) != null) {
            ftpList.add(fileName);
        }
        return ftpList;
    }
    
    /** Get the response code from the last command that was sent */
    public int getResponseCode() throws NumberFormatException {
        return Integer.parseInt(getResponseString().substring(0, 3));
    }
    
    /** Return true if the last response code was in the 200 range, 
      * false otherwise */
    public boolean isValidResponse() {
        try {
            int respCode = getResponseCode();
            return (respCode  >= 200 &amp;&amp; respCode < 300);
        } catch (Exception e) {
            return false;
        }
    }
    
    /** Send a raw FTP command to the server. You can get the response
      * by calling getResponseString (which returns the entire response as a
      * single String) or getResponseStrings (which returns the response
      * as a Vector). */
    public int issueRawCommand (String command) throws IOException {
        return issueCommand(command);
    }
    
    /** Download a file from the server, and save it to the specified local file */
    public boolean downloadFile (String serverFile, String localFile) throws IOException {
        int i = 0;
        byte[] bytesIn = new byte[1024];
        BufferedInputStream in = new BufferedInputStream(get(serverFile));
        FileOutputStream out = new FileOutputStream(localFile);
        while ((i = in.read(bytesIn)) >= 0) {
            out.write(bytesIn, 0, i);
        }
        out.close();
        return true;
    }
    
    /** Upload a file to the server */
    public boolean uploadFile (String localFile, String serverFile) throws IOException {
        int i = 0;
        byte[] bytesIn = new byte[1024];
        FileInputStream in = new FileInputStream(localFile);
        BufferedOutputStream out = new BufferedOutputStream(put(serverFile));
        while ((i = in.read(bytesIn)) >= 0) {
            out.write(bytesIn, 0, i);
        }
        in.close();
        out.close();
        return true;
    }
}



Merci d'avance.

10 réponses

sheorogath Messages postés 2448 Date d'inscription samedi 21 février 2004 Statut Modérateur Dernière intervention 29 janvier 2010 17
29 févr. 2008 à 16:55
               ftp.downloadFile("25.jpg", "C:\\Employes\\25.jpg");

"n'est pas mort ce qui semble a jamais dormir et en d'etrange temps meme la mort peut mourrir"
0
mimi1255 Messages postés 87 Date d'inscription mardi 22 janvier 2008 Statut Membre Dernière intervention 14 mars 2024
2 mars 2008 à 17:01
ok je vous remercie, ce problème est résolu. Mais maintenant j'ai un autre problème, j'ai cette erreur qui apparaît:

java.io.FileNotFoundException: QUIT: 550 can't access file.

merci encore.
0
sheorogath Messages postés 2448 Date d'inscription samedi 21 février 2004 Statut Modérateur Dernière intervention 29 janvier 2010 17
2 mars 2008 à 17:12
morceau de code en cause ?

"n'est pas mort ce qui semble a jamais dormir et en d'etrange temps meme la mort peut mourrir"
0
mimi1255 Messages postés 87 Date d'inscription mardi 22 janvier 2008 Statut Membre Dernière intervention 14 mars 2024
2 mars 2008 à 17:35
je pense car si je me connecte au serveur ftp en passant par un navigateur internet je n'ai pas de problème.
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
sheorogath Messages postés 2448 Date d'inscription samedi 21 février 2004 Statut Modérateur Dernière intervention 29 janvier 2010 17
2 mars 2008 à 17:37
nan mais en fait quel est le morceau de code qui te declenche l'erreur ...?

"n'est pas mort ce qui semble a jamais dormir et en d'etrange temps meme la mort peut mourrir"
0
mimi1255 Messages postés 87 Date d'inscription mardi 22 janvier 2008 Statut Membre Dernière intervention 14 mars 2024
2 mars 2008 à 18:06
ce n'est pas pour ce code là, c'est pour un autre code où j'ai rajouté un bouton. Le voici:

mon 1er fichier: (c'est un jframe):

/*
 * FtpWrapperTest.java
 *
 * Created on 29 février 2008, 09:29
 */

package testftp;

import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.lang.*;
import testftp.SunFtpWrapper;
/**
 *
 * @author  GRESLON Jérémy
 */
public class FtpWrapperTest extends javax.swing.JFrame {
    
    /** Creates new form FtpWrapperTest */
    public FtpWrapperTest() {
        initComponents();
    }
    

    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanelPhoto = new javax.swing.JPanel();
        jButtonBadge = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanelPhoto.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        org.jdesktop.layout.GroupLayout jPanelPhotoLayout = new org.jdesktop.layout.GroupLayout(jPanelPhoto);
        jPanelPhoto.setLayout(jPanelPhotoLayout);
        jPanelPhotoLayout.setHorizontalGroup(
            jPanelPhotoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 210, Short.MAX_VALUE)
        );
        jPanelPhotoLayout.setVerticalGroup(
            jPanelPhotoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 216, Short.MAX_VALUE)
        );

        jButtonBadge.setText("Passage du badge");
        jButtonBadge.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBadgeActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(83, 83, 83)
                        .add(jPanelPhoto, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .add(133, 133, 133)
                        .add(jButtonBadge)))
                .addContainerGap(103, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(34, 34, 34)
                .add(jPanelPhoto, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jButtonBadge)
                .addContainerGap(12, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

  
    
    private void jButtonBadgeActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
        try {
            SunFtpWrapper ftp = new SunFtpWrapper();
            String serverName = "127.0.0.1";
            ftp.openServer(serverName);
            if (ftp.serverIsOpen()) {
                System.out.println("Connecte à " + serverName);
                try {
                    ftp.login("GARDIEN", "admin");
                    System.out.println("Message de bienvenue:\n" + ftp.welcomeMsg);
                    System.out.println("Répertoire courrant: " + ftp.pwd());
                    System.out.println("Listage du répértoire:\n" + ftp.listRaw());
                    System.out.println("Téléchargement de bmw.jpg");
                    ftp.ascii();
                    ftp.downloadFile("25.jpg", "C:\\Documents and Settings\\GRESLON Jérémy\\Mes documents\\Photos_employes\\25.jpg");
                                        
                                       
                } catch (Exception ftpe) {
                    ftpe.printStackTrace();
                } finally {
                                         ImageIcon icone = new ImageIcon("25.jpg");
                                        JLabel image = new JLabel(icone);
                                        image.setSize(jPanelPhoto.getWidth(), jPanelPhoto.getHeight());
                                        jPanelPhoto.add(image);
                                        jPanelPhoto.repaint();
                                        
                    ftp.closeServer();
                }
            } else {
                System.out.println("Impossible de se connecter à" + serverName);
            }
            System.out.println("Fin");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }                                            
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FtpWrapperTest().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButtonBadge;
    private javax.swing.JPanel jPanelPhoto;
    // End of variables declaration                   
    
}



mon 2ème fichier:


/* <!-- in case someone opens this in a browser... -->  */
package testftp;

import java.util.Vector;
import java.io.*;
import sun.net.ftp.FtpClient;

/**
  * This is a basic wrapper around the sun.net.ftp.FtpClient
  * class, which is an undocumented class which is included
  * with Sun Java that allows you to make FTP connections
  * and file transfers.
  * 
  * Program version 1.0. Author Julian Robichaux, http://www.nsftools.com
  *
  * @author Julian Robichaux ( http://www.nsftools.com )
  * @version 1.0
  */
public class SunFtpWrapper extends FtpClient {
    /*
     * Methods you might use from the base FtpClient class
     * // set the transfer type to ascii
     * public void ascii()
     * 
     * // set the transfer type to binary
     * public void binary()
     * 
     * // change to the specified directory
     * public void cd(String remoteDirectory)
     * 
     * // close the connection to the server
     * public void closeServer()
     * 
     * // download the specified file from the FTP server
     * public TelnetInputStream get(String filename)
     * 
     * // return the last response from the server as a single String
     * public String getResponseString()
     * 
     * // return the last response from the server as a Vector of Strings
     * public Vector getResponseStrings()
     * 
     * // list the contents of the current directory (could be in any number
     * // of formats, depending on the remote server)
     * public TelnetInputStream list()
     * 
     * // login to the FTP server, using the specified username and password
     * public void login(String username, String password)
     * 
     * // open a connection to the specified FTP server, using port 21
     * public void openServer(String host)
     * 
     * // open a connection to the specified FTP server, using the specified port
     * public void openServer(String host, int port))
     * 
     * // upload a file to the FTP server (the uploaded file will have the specified
     * // file name
     * public TelnetOutputStream put(String filename)
     */
    
    /** Get the present working directory */
    public String pwd() throws IOException {
        issueCommand("PWD");
        if (isValidResponse()) {
            String response = getResponseString().substring(4).trim();
            if (response.startsWith("""))
                response = response.substring(1);
            if (response.endsWith("""))
                response = response.substring(0, response.length() - 1);
            return response;
        } else {
            return "";
        }
    }
    
    /** Go up one directory */
    public boolean cdup() throws IOException {
        issueCommand("CDUP");
        return isValidResponse();
    }
    
    /** Create a new directory */
    public boolean mkdir (String newDir) throws IOException {
        issueCommand("MKDIR " + newDir);
        return isValidResponse();
    }
    
    /** Delete a remote file */
    public boolean deleteFile (String fileName) throws IOException {
        issueCommand("DELETE " + fileName);
        return isValidResponse();
    }
    
    /** Get the results of the LIST command as a Vector of Strings. 
      * Because there's no standard format for the results of a LIST
      * command, it's hard to tell what resulting data will look like.
      * Just be aware that different servers have different ways of
      * returning your LIST data. */
    public Vector listRaw() throws IOException {
        String fileName;
        Vector ftpList = new Vector();
        BufferedReader reader = new BufferedReader(new InputStreamReader(list()));
        while ((fileName = reader.readLine()) != null) {
            ftpList.add(fileName);
        }
        return ftpList;
    }
    
    /** Get the response code from the last command that was sent */
    public int getResponseCode() throws NumberFormatException {
        return Integer.parseInt(getResponseString().substring(0, 3));
    }
    
    /** Return true if the last response code was in the 200 range, 
      * false otherwise */
    public boolean isValidResponse() {
        try {
            int respCode = getResponseCode();
            return (respCode  >= 200 &amp;&amp; respCode < 300);
        } catch (Exception e) {
            return false;
        }
    }
    
    /** Send a raw FTP command to the server. You can get the response
      * by calling getResponseString (which returns the entire response as a
      * single String) or getResponseStrings (which returns the response
      * as a Vector). */
    public int issueRawCommand (String command) throws IOException {
        return issueCommand(command);
    }
    
    /** Download a file from the server, and save it to the specified local file */
    public boolean downloadFile (String serverFile, String localFile) throws IOException {
        int i = 0;
        byte[] bytesIn = new byte[1024];
        BufferedInputStream in = new BufferedInputStream(get(serverFile));
        FileOutputStream out = new FileOutputStream(localFile);
        while ((i = in.read(bytesIn)) >= 0) {
            out.write(bytesIn, 0, i);
        }
        out.close();
        return true;
    }
    
    /** Upload a file to the server */
    public boolean uploadFile (String localFile, String serverFile) throws IOException {
        int i = 0;
        byte[] bytesIn = new byte[1024];
        FileInputStream in = new FileInputStream(localFile);
        BufferedOutputStream out = new BufferedOutputStream(put(serverFile));
        while ((i = in.read(bytesIn)) >= 0) {
            out.write(bytesIn, 0, i);
        }
        in.close();
        out.close();
        return true;
    }
}



En mode design, j'ai un bouton "passage du badge" et un panel juste au-dessus où je souhaiterai afficher l'image.

Le problème survient lorsque je clique sur le bouton. Si je teste le programme sans le bouton, il n'y a pas de problème.

Merci encore une fois.
0
mimi1255 Messages postés 87 Date d'inscription mardi 22 janvier 2008 Statut Membre Dernière intervention 14 mars 2024
2 mars 2008 à 22:54
pouvez-vous m'aider s'il vous plait ?

Je vous remercie
0
sheorogath Messages postés 2448 Date d'inscription samedi 21 février 2004 Statut Modérateur Dernière intervention 29 janvier 2010 17
3 mars 2008 à 12:26
je sais pas moi
un FileNotFound c'est qu'il a pas trouver ton fichier apres je sais aps si c sur le serveur ou sur ton pc
regarde ca deja et on verra

"n'est pas mort ce qui semble a jamais dormir et en d'etrange temps meme la mort peut mourrir"
0
mimi1255 Messages postés 87 Date d'inscription mardi 22 janvier 2008 Statut Membre Dernière intervention 14 mars 2024
3 mars 2008 à 20:10
en faite, si en testant le code, on peut s'aperçevoir que lorsqu'on clique plusieurs fois sur le bouton "passage du badge" alors j'arrive bien à voir mon fichier.

Comment celà s'explique-t-il ?

Merci d'avance.
0
mimi1255 Messages postés 87 Date d'inscription mardi 22 janvier 2008 Statut Membre Dernière intervention 14 mars 2024
3 mars 2008 à 21:14
enfin je ne comprend pas pourriez-vous tester mon code?
0
Rejoignez-nous