我正在尝试使用URLConnection将文件上传到FTP服务器。没有抛出异常。我似乎能够连接到服务器。如果我"手动"上传(使用FTP客户端),我可以下载该文件(使用另一个程序)而不会出现问题。
我使用BufferedOutputStream.write(int)。日志显示我可以读取本地文件(其中包含"Hej-Hej")并访问其中的字节。问题是:没有任何内容写入服务器文件。当我在服务器上读取文件时,它仍然包含预上传的内容。文件未更新。我尝试了BufferedOutputStream.write(String.getBytes()),但没有帮助。
static public void upload(String string, String file) {
File file_ = new File(Environment.getExternalStorageDirectory() + "/Android/data/org.sionlinkoping.pingstprayer/files/thanks.txt");
try {
upload("ftphome.mah.se", user, passwd, "thanks.txt", file_);
}
catch(Exception e) { Log.d("",e.toString()); }
}
static public void upload( String ftpServer, String user, String password,
String fileName, File source ) throws MalformedURLException,
IOException
{
if (ftpServer != null && fileName != null && source != 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 );
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
URL url = new URL( sb.toString() );
URLConnection urlc = url.openConnection();
bos = new BufferedOutputStream( urlc.getOutputStream() );
bis = new BufferedInputStream( new FileInputStream( source ) );
int i;
// read byte by byte until end of stream
while ((i = bis.read()) != -1)
{
Log.d("","i:"+i);
bos.write( i );
}
bos.flush();
}
finally
{
if (bis != null)
try
{
bis.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
if (bos != null)
try
{
bos.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
else
{
System.out.println( "Input not available." );
}
}
日志显示:
01-07 14:00:50.662: DEBUG/(6925): i:239
01-07 14:00:50.662: DEBUG/(6925): i:187
01-07 14:00:50.662: DEBUG/(6925): i:191
01-07 14:00:50.662: DEBUG/(6925): i:72
01-07 14:00:50.662: DEBUG/(6925): i:101
01-07 14:00:50.662: DEBUG/(6925): i:106
01-07 14:00:50.662: DEBUG/(6925): i:32
01-07 14:00:50.662: DEBUG/(6925): i:104
01-07 14:00:50.662: DEBUG/(6925): i:101
01-07 14:00:50.662: DEBUG/(6925): i:106
01-07 14:00:50.672: DEBUG/(6925): i:10
问题在于您的假设,即写入FTP URL将导致文件保存到服务器。不会的。结果只是没有定义——它不是这样工作的。
有可用的FTP库;你需要用一个。例如,请参见此处。