使用java检查是否存在带有“ftp”url的文件

时间:2013-08-19 14:35:14

标签: java file url ftp

拜托,有谁能告诉我,我怎样才能检查文件是否存在于只有FTP协议的URL上?我使用这段代码:

   public boolean exists(String URLName) throws IOException {
        input = null;
        boolean result = false;
        try {
            input = new URL(URLName).openStream();
            System.out.println("SUCCESS");
            result = true;
        } catch (Exception e) {
            System.out.println("FAIL");
        } finally {
            if (input != null) {
                input.close();
                input = null;
            }
        }
        return result;
    }

当我发送的内容超过一两个时,它不起作用,它只是sais

    sun.net.ftp.FtpProtocolException: Welcome message: 421 Too many connections (2) from this IP

        at sun.net.ftp.FtpClient.openServer(FtpClient.java:490)
        at sun.net.ftp.FtpClient.openServer(FtpClient.java:475)


at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.java:270)
    at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnection.java:352)
    at java.net.URL.openStream(URL.java:1010)
    at bibparsing.PDFImage.exists(PDFImage.java:168)
    at bibparsing.PDFImage.main(PDFImage.java:189)

当协议是HTTP时,它很有用。我的意思是地址:

ftp://cmp.felk.cvut.cz/pub/cmp/articles/chum/Chum-TR-2001-27.pdf ftp://cmp.felk.cvut.cz/pub/cmp/articles/martinec/Kamberov-ISVC2006.pdf 和那样的东西

1 个答案:

答案 0 :(得分:3)

这里的问题是这种方法不是线程安全;如果两个线程同时使用此方法,则可以覆盖名为 input 的实例变量,导致另一个线程不关闭它打开的连接(并且不关闭任何内容,或者由另一个线程打开连接)。

通过将输入变量设为local:

,可以轻松修复此问题
InputStream input=null;
方法中的

代码样式:,您可以在知道后立即返回结果。初学者通常首先声明变量,然后执行逻辑并在方法结束时返回结果。

可以节省大量代码和复杂性
  • 尽可能晚地声明变量 (当你第一次需要它们时)
  • 声明尽可能少的变量(可读性始终是添加变量的一个很好的理由,但变量越少意味着复杂性越来越低)
  • 一旦您知道结果返回(减少代码中的路径,从而降低复杂性)

代码可以简单地写成:

public static boolean exists (String urlName) throws IOException {
    try {
        new URL(urlName).openStream().close();
        return true;
    } catch (IOException e) {
        return false;
    }
}