Java 从HDFS读取文件时出现格式错误的异常

Java 从HDFS读取文件时出现格式错误的异常,java,hadoop,Java,Hadoop,我有下面的测试程序从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,

我有下面的测试程序从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)
线程“main”java.net.MalformedURLException中的异常:未知协议:hdfs 位于java.net.URL。(URL.java:592) 位于java.net.URL。(URL.java:482) 在java.net.URL.(URL.java:431) 位于in.ksharma.hdfs.FileReader.main(FileReader.java:29)
注册Hadoop的Url处理程序。标准Url处理程序不知道如何处理hdfs://scheme

试试这个:

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();
        }
    }

我在Hadoop2.6上编写一个Java应用程序来读取hdfs时遇到了同样的问题。 我的解决方案是:添加

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

在我们的案例中,我们必须将其与其他答案结合起来:

因此,首先在我们的HDFS设置类(
Scala code
)中:

后来,就像在公认的答案中:


旁注:

我们已经:
“org.apache.hadoop”%“hadoop hdfs”%“2.8.0”
在我们的依赖项中,它没有帮助。

我尝试了此代码,但仍然得到异常:
未知协议:hdfs
。请告诉我您是如何解决此问题的。这是删除错误所必需的步骤。我看不出有什么理由否决这项议案。为我工作。
val hadoopConfig: Configuration = new Configuration()
hadoopConfig.set("fs.hdfs.impl", classOf[DistributedFileSystem].getName)
hadoopConfig.set("fs.file.impl", classOf[LocalFileSystem].getName)
URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory)
Try(new URL(path))