2013-11-15 45 views
0

我用下面的代码片段下载PDF文件(我把它从here,学分Josh M如何区分pdf和非pdf文件?

public final class FileDownloader { 

    private FileDownloader(){} 

    public static void main(String args[]) throws IOException{ 
     download("http://pdfobject.com/pdf/sample.pdf", new File("sample.pdf")); 
    } 

    public static void download(final String url, final File destination) throws IOException { 
     final URLConnection connection = new URL(url).openConnection(); 
     connection.setConnectTimeout(60000); 
     connection.setReadTimeout(60000); 
     connection.addRequestProperty("User-Agent", "Mozilla/5.0"); 
     final FileOutputStream output = new FileOutputStream(destination, false); 
     final byte[] buffer = new byte[2048]; 
     int read; 
     final InputStream input = connection.getInputStream(); 
     while((read = input.read(buffer)) > -1) 
      output.write(buffer, 0, read); 
     output.flush(); 
     output.close(); 
     input.close(); 
    } 
} 

它可以完美兼容PDF文件。然而,正如我遇到一个“坏档案”......我不知道该文件的扩展名是什么,但似乎我陷入了无限循环while((read = input.read(buffer)) > -1)。我该如何改进这个片段来丢弃任何不适当的文件(非pdf)?

+0

*它适用于pdf文件。但是,正如我遇到一个“坏档案”* - 您是否检查过这是否真的是PDF还是PDF的问题?你在这种情况下检查过目标文件的内容吗? – mkl

回答

2

还有一个类似问题的问题:Infinite Loop in Input Stream

查看可能的解决方案:Abort loop after fixed time

您可以尝试设置连接的超时时间:Java URLConnection Timeout

+0

+1谢谢。这种解决方案适用于小批量生产。但是,为每次下载启动一个新线程将是不切实际的。我有大约3700万个文件需要检查 –

+0

我已经用另一个可能的解决方案更新了答案。 –