将文件上传到FTP服务器时出现异常
我想要做的是使用java代码上传一个简单的文本文件到FTP服务器,但出现错误。我正在努力使其工作,但无法做到这一点。以下是代码。将文件上传到FTP服务器时出现异常
File file = new File("testFile.txt");
FileOutputStream fo = new FileOutputStream(file);
PrintStream ps = new PrintStream(fo);
ps.println("BLA");
ps.close();`enter code here`
fo.close();
uploadFile(file,file.getName());
public void upload(String ftpServer, String user, String password,
String fileName, FileInputStream is) throws MalformedURLException,
IOException
{
log("inside upload...........");
if (ftpServer != null && fileName != null && is != null)
{
StringBuffer sb = new StringBuffer("ftp://");
// check for authentication else assume its anonymous access.
if (user != null && password != null)
{
sb.append(user);
sb.append(':');
sb.append(password);
sb.append('@');
}
sb.append(ftpServer);
sb.append('/');
sb.append(fileName);
/*
* type ==> a=ASCII mode, i=image (binary) mode, d= file directory
* listing
*/
sb.append(";type=i");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
URL url = new URL(sb.toString());
URLConnection urlc = url.openConnection();
log("urlc::1 "+urlc);
bos = new BufferedOutputStream(urlc.getOutputStream());
log("bos:: "+bos);
bis = new BufferedInputStream(is);
int i;
// read byte by byte until end of stream
while ((i = bis.read()) != -1)
{
log("i"+i);
bos.write(i);
}
}
finally
{
if (bis != null)
try
{
bis.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
if (bos != null)
try
{
bos.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
else
{
log("Input not available.");
}
}
有关更多详细信息,我正在使用java.net导入。
我得到错误:
Exception e is :: java.io.IOException: illegal filename for a PUT
at sun.net.www.protocol.ftp.FtpURLConnection.getOutputStream(Unknown Source)
at ToolFileUpload.upload(ToolFileUpload.java:72)
at APInterfaceTool.uploadFile(APInterfaceTool.java:861)
at APInterfaceTool.createInvoiceTextFile(APInterfaceTool.java:613)
at APInterfaceTool.generateOutBoundExtract(APInterfaceTool.java:426)
在FtpURLConnection.getOutputStream
抛出异常的代码是:
decodePath(url.getPath());
if (filename == null || filename.length() == 0) {
throw new IOException("illegal filename for a PUT");
}
正如你所看到的,问题是,已经被解析出来的filename
组件的网址为空或缺失。
最可能的原因是您正在向upload
方法提供不适当的参数。不幸的是,你没有包含调用该方法的代码,所以我不能再进一步了。
我从日志中检查过既没有文件名也没有文件长度为零。此外,我已将整个方法放在上面。它是一种名为上传的方法。 – 2012-04-23 11:21:16
我想这个独立的程序上传文件到FTP服务器。代码运行正常,但文件不是在FTP上创建的 – 2012-04-23 11:40:15
非常感谢您的支持。我发现这个问题与FTP服务器相同,因为相同的代码在其他FTP服务器上运行良好。 :D – 2012-04-23 12:58:54
当你调用该函数时,你确定你传递的参数FileInputStream is
不为空吗?
是的,我检查它不是null。可能是什么问题呢 ? – 2012-04-23 11:33:46
它必须是代码试图创建一个已经存在的文件。我想[这](http://www.coderanch.com/t/277808/Streams/java/Copy-file-window-machine-Linux)可能会有所帮助。 – 2012-04-23 12:03:12
我发现这个问题与FTP服务器有关。我在其他FTP服务器上尝试了相同的代码,它工作正常。感谢大家的帮助。 – 2012-04-23 12:57:53
'java.io.IOException:PUT的非法文件名' 只要您的文件是'null'或其名称的长度为'0',就会发生。在这些线上进行调试。 – Dilawar 2012-04-23 10:26:53
我发现问题是与FTP服务器。我在其他FTP服务器上尝试了相同的代码,它工作正常。谢谢大家的帮助 – 2012-04-23 13:04:54