开发者

java ftp nullpointer exception

I have code to upload a file to a server.

import org.apache.commons.net.ftp.FTPClient;

    import java.io.File;
    import java.io.IOException;
    import org.apache.commons.net.ftp.FTPFile;
    import java.io.FileInputStream;
    import java.net.SocketException;

    public class FtpConnectDemo {
        public static void main(String[] args) throws SocketException, IOException{
            FTPClient client = new FTPClient();
            FileInputStream fis = null;

            client.connect("ftp.someserver.co.uk",21);
            boolean login = client.login("webmaster@someserver.co.uk",
                    "mypassword");


            String filename = "E:/workbench j2ee/cPEP_UI/WebContent/engine.xml";
            client.storeFile(filename, fis);
            client.logout();
            fis.close();
        }
    }

and when I run this code, it is giving me this error:

Exception in thread "main" java.lang.Null开发者_如何学运维PointerException
    at FtpConnectDemo.main(FtpConnectDemo.java:22)

The username, password, servername are all right. What's wrong then? I am able to connect to FTP using telnet. Any ideas?

EDIT 1

OK, now I am not getting the nullpointer exception, as I initialized fis. But my file is not uploaded yet; what might be the problem?


You never instanciate your variable fis. I think that this is your problem here.

This cause two problems:

  • You try to store null as a file, line 20. This is handled by the Apache FTP library you are using.
  • NullPointerException line 22, when you try to call close().

Also, other thing I'd like to point out: line 20, when you are calling storeFile. The path you are giving is a path pointing to a local file. I think you should put the remote file path in here.

The final code should look like this:

// ...

FileInputStream fis = new FileInputStream("E:/workbench j2ee/cPEP_UI/WebContent/engine.xml");

// ...

client.storeFile("engine.xml", fis);

// ...


you are missing

fis = new FileInputStream(new File(filename));

before client.storeFile()


Looks like your fis cannot be anything other than null (you only initialise it with null), so the NullPointerException is natural when you try to execute close() on it.


The sendFile method on client.storeFile returns a boolean. I would first check that value to see if it is failing or maybe just importing to somewhere you're not expecting.

The client also has a getReplyCode and getReplyString methods which you could use to see what the server is up to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜