[英]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.NullPointerException
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.
我可以使用telnet连接到FTP。 Any ideas?
有任何想法吗?
OK, now I am not getting the nullpointer exception, as I initialized fis
. 好了,现在我没有得到的空指针例外,因为我初始化
fis
。 But my file is not uploaded yet; 但是我的文件尚未上传; what might be the problem?
可能是什么问题?
You never instanciate your variable fis
. 您永远不会实例化变量
fis
。 I think that this is your problem here. 我认为这是您的问题。
This cause two problems: 这导致两个问题:
null
as a file, line 20. This is handled by the Apache FTP library you are using. null
存储为文件,第20行。这由您使用的Apache FTP库处理。 NullPointerException
line 22, when you try to call close()
. NullPointerException
第22行,当您尝试调用close()
。 Also, other thing I'd like to point out: line 20, when you are calling storeFile
. 另外,我想指出的另一点是:第20行,当您调用
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()
在
client.storeFile()
之前
看起来您的fis
不能是null
以外的任何内容(只能使用null
初始化它),因此当您尝试对其执行close()
时, NullPointerException
是自然的。
The sendFile method on client.storeFile returns a boolean. client.storeFile上的sendFile方法返回一个布尔值。 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. 客户端还具有getReplyCode和getReplyString方法,可用于查看服务器的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.