从HDFS读取文件时出现了MalformedURLException

5
我有以下的测试程序,可以从HDFS读取文件。
public class FileReader {
    public static final String NAMENODE_IP = "172.32.17.209";
    public static final String FILE_PATH = "/notice.html";

    public static void main(String[] args) throws MalformedURLException,
            IOException {
        String url = "hdfs://" + NAMENODE_IP + FILE_PATH;

        InputStream is = new URL(url).openStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line = br.readLine();
        while(line != null) {
            System.out.println(line);
            line = br.readLine();
        }
    }
}

它报告了 java.net.MalformedURLException

Exception in thread "main" java.net.MalformedURLException: unknown protocol: hdfs
    at java.net.URL.<init>(URL.java:592)
    at java.net.URL.<init>(URL.java:482)
    at java.net.URL.<init>(URL.java:431)
    at in.ksharma.hdfs.FileReader.main(FileReader.java:29)
3个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
9

注册Hadoop的URL处理程序。标准的URL处理程序不知道如何处理hdfs://协议。

尝试以下操作:

public static void main(String[] args) throws MalformedURLException,
            IOException {
        URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());

        String url = "hdfs://" + NAMENODE_IP + FILE_PATH;

        InputStream is = new URL(url).openStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line = br.readLine();
        while(line != null) {
            System.out.println(line);
            line = br.readLine();
        }
    }

我尝试了这段代码,但仍然出现异常:unlnown protocol: hdfs。请告诉我您是如何解决这个问题的。 - user182944

3
在为读取Hadoop 2.6上的HDFS编写Java应用程序时,我遇到了相同的问题。 我的解决方案是:添加

 hadoop-2.X/share/hadoop/hdfs/hadoop-hdfs-2.X.jar to your classpath.

这是消除错误所必需的步骤。我看不出为什么会被踩。对我有用。 - Sushant Gupta

2
在我们的情况下,我们需要将它与其他答案结合起来:
https://dev59.com/QmQm5IYBdhLWcg3w4CMN#21118824 因此,首先在我们的 HDFS 配置类(Scala 代码)中:
val hadoopConfig: Configuration = new Configuration()
hadoopConfig.set("fs.hdfs.impl", classOf[DistributedFileSystem].getName)
hadoopConfig.set("fs.file.impl", classOf[LocalFileSystem].getName)
之后,就像接受的答案中所述:
https://dev59.com/AYPba4cB1Zd3GeqPupxp#25971334
URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory)
Try(new URL(path))

注意:

我们已经在我们的依赖项中添加了"org.apache.hadoop" % "hadoop-hdfs" % "2.8.0",但它没有起到作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,