[英]Why does the FTP download not work properly with Java
我目前正在开发一个用 Java 编写的小型清单生成器程序。 我想将创建的文件上传和下载到我的 FTP 服务器 (ftps)。 我正在使用以下代码进行下载:
public static void downloadfile(){
FTPSClient con = null;
System.out.println("Download Status: 5%");
try
{
System.out.println("Download Status: 20%");
con = new FTPSClient();
con.connect(url);
if (con.login(user, psw))
{
System.out.println("Download Status: 50%");
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "E:\\Downloads\\Testdokument.txt";
OutputStream out = new FileOutputStream(new File(data));
boolean result = con.retrieveFile("Testdokument.txt", out);
out.close();
System.out.println(result);
if (result) {
System.out.println("Download Status: 100%");
} else if(result == false) {
System.out.println("Download won't work");
}
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
System.out.println("download failed");
e.printStackTrace();
}
}
问题是下载本身工作正常。 但是下载的文件是空的。 如果我用图像尝试它不是“可读的”。 相反,上传工作完美。 我使用 Apache 通用 IO 库来实现 FTP 功能。
如果我下载文件,控制台会显示第一个状态 5%、20%、50%,然后在添加错误语句后,下载将不起作用...
我不知道为什么文件本身正在下载但不包含任何内容。
有任何想法吗?
您没有正确使用 java 中的资源。
任何时候创建代表资源的对象时,都必须关闭它。 您打开一个新的FileOutputStream
,这是一个资源。 任何实现AutoCloseable
的资源绝对是您必须关闭的资源。 尝试这个:
try (OutputStream out = new FileOutputStream(data /* no need to wrap in File */)) {
// do your stuff with out here
}
第二个注意事项:您的异常处理很糟糕; 请停止犯这个常见的错误。 异常包含 4 个有用的信息位:类型、消息、跟踪和原因。 您实际上是将 4 个中的 3 个扔进垃圾箱。 只需将throws Exception
添加到您的 main 方法和您的downloadFile
方法。 它可以节省您的输入并使您的错误消息更有用。
我找到了解决方案。
我添加了以下两件事,现在可以使用了
con.execPBSZ(0);
con.execPROT("P");
不知道这代表什么,但我会找出来。
我知道这个答案是题外话,但我想为用户 rzwitserloot 提供一个示例,它表明printStackTrace()
不会隐藏任何重要信息。 这不适合评论:
public class Main
{
public static void doSomething()
{
int array[] = {1, 2, 3};
int b = array[3]; // throws Exception
}
public static void test() throws Exception
{
try
{
doSomething();
}
catch (Exception e)
{
throw new Exception("something bad happened", e);
}
}
public static void main(String[] args) throws Exception
{
try
{
test();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
产生输出:
java.lang.Exception: something bad happened
at Main.test(Main.java:18)
at Main.main(Main.java:26)
Caused by: java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Main.doSomething(Main.java:7)
at Main.test(Main.java:14)
... 1 more
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.