OpenConnection不会导入完整内容

时间:2013-03-01 10:47:01

标签: java file-io

我想从网址导入xml文件。

我的代码是:

URL url = new URL(partnersEntity.getUrl());

            URLConnection urlConnection = url.openConnection();
            urlConnection.setReadTimeout(55000);


            File file = new File(fileURL);


            FileWriter writer = new FileWriter(file);

            IOUtils.copy(urlConnection.getInputStream(), writer);

问题是,XML文件有60000行,但我的导出只保存了11000行。

问题出在哪里?

我可以设置内容长度吗?

1 个答案:

答案 0 :(得分:0)

所有输入输出对象都是应该关闭的资源,否则您将有资源泄漏或丢失未刷新的缓冲区(您的情况)。它应该在try-finally块中完成。对于您的场景:

URL url = new URL(partnersEntity.getUrl());
URLConnection urlConnection = url.openConnection();
urlConnection.setReadTimeout(55000);

InputStream is = urlConnection.getInputStream();    
try
{
    File file = new File(fileURL);
    FileWriter writer = new FileWriter(file);
    try
    {
        IOUtils.copy(is, writer);
    }
    finally
    {
        IOUtils.closeQuietly(writer);
    }
}
finally
{
    IOUtils.closeQuietly(is);
}

在Java 7中,您可以使用新的try-syntax:

URL url = new URL(partnersEntity.getUrl());
URLConnection urlConnection = url.openConnection();
urlConnection.setReadTimeout(55000);


File file = new File(fileURL);

try(
    InputStream is = urlConnection.getInputStream();
    FileWriter writer = new FileWriter(file);
)
{
    IOUtils.copy(is, writer);
}