我想要做的是使用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)
'java.io.IOException:PUT的非法文件名' 只要您的文件是'null'或其名稱的長度爲'0',就會發生。在這些線上進行調試。 – Dilawar 2012-04-23 10:26:53
我發現問題是與FTP服務器。我在其他FTP服務器上嘗試了相同的代碼,它工作正常。謝謝大家的幫助 – 2012-04-23 13:04:54