简体   繁体   English

通过将文件名附加到基本URL来从服务器目录中读取文件

[英]Reading a file from server's directory by appending filename to base URL

I have written a method which reads a file from server and it was working fine but now I have modified it to take a filename as parameter and read that file from server. 我已经编写了一种从服务器读取文件的方法,并且工作正常,但是现在我已对其进行了修改,以将文件名作为参数并从服务器读取该文件。 It is a boolean method which returns false if the file was not found on server directory. 这是一个布尔方法,如果在服务器目录上找不到该文件,则返回false。 The problem is, it is catching an exception I don't know what could be the possible reason for it because the file is present on the server directory any help would be grateful. 问题是,它捕获了一个异常,我不知道可能是什么原因,因为服务器目录中存在该文件,因此不胜感激。

public final boolean readDataFromServer (String fileName)
{
    try
    {
        String url = "http://example.com/FolderName/".concat(fileName);
        URL webServer = new URL (url);
        Scanner reader = new Scanner(webServer.openStream());

        // reading data in variables by using nextLine() method

        reader.close();
        return true;
     }

     catch (MalformedURLException e)
    {
        return false;
    }
    catch (IOException e)
    {
        JOptionPane.showMessageDialog(null,"The file was not found on the server");
        return false;
    }
    catch (Exception e)     // this is the block where I'm getting an exception
    {
        System.out.println("Exception here");
        return false;

    }
}

EDIT: I tried to print the exception and I got this: "java.util.NoSuchElementException: No line found" while the file present on my server is accessible and has data in it. 编辑:我试图打印异常,我得到了:“ java.util.NoSuchElementException:找不到行”,而服务器上存在的文件是可访问的并且包含数据。

It is working fine now. 现在工作正常。 The problem was the loop which was reading the data I called hasNextLine() method from scanner class in the condition and it worked perfectly. 问题是循环正在条件下从扫描程序类读取我称为hasNextLine()方法的数据,并且它运行良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM