无法写入连接到URLConnection的BufferedOutputStream

时间:2012-01-07 13:43:44

标签: java android ftp urlconnection

我正在尝试使用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

1 个答案:

答案 0 :(得分:2)

问题在于您假设写入FTP URL会导致文件保存到服务器。它不会。结果只是未定义 - 它不起作用。

有FTP库可用;你需要使用一个。例如,请参阅here.