No FileSystem for scheme:file解决方法

No FileSystem for scheme:file解决方法

        import java.io.BufferedReader;
        import java.io.InputStreamReader;
 
        import org.apache.hadoop.conf.Configuration;
        import org.apache.hadoop.fs.FileSystem;
        import org.apache.hadoop.fs.Path;
        import org.apache.hadoop.fs.FSDataInputStream;
 
        public class Chapter3 {
                public static void main(String[] args) {
                        try {
                                Configuration conf = new Configuration();
                                conf.set("fs.defaultFS","hdfs://localhost:9000");
                                conf.set("fs.hdfs.impl","org.apache.hadoop.hdfs.DistributedFileSystem");
                                FileSystem fs = FileSystem.get(conf);
                    byte[] buff = "Hello world".getBytes(); // 要写入的内容
                                String filename = "test"; //要写入的文件名
                                FSDataOutputStream os = fs.create(new Path(filename));
                                os.write(buff,0,buff.length);
                                System.out.println("Create:"+ filename);
                                os.close();
                                Path file = new Path("test"); 
                                FSDataInputStream getIt = fs.open(file);
                                BufferedReader d = new BufferedReader(new InputStreamReader(getIt));
                                String content = d.readLine(); //读取文件一行
                                System.out.println(content);
                                d.close(); //关闭文件
                                fs.close(); //关闭hdfs
                        } catch (Exception e) {
                                e.printStackTrace();
                        }
                }
        }

今天在测试如上代码时出现了一个错误:eclipse中可以正常运行,“hadoop jar”命令也可以正常运行

cd /usr/local/hadoop
./bin/hadoop jar ./myapp/HDFSExample.jar

但是“java”命令

cd /usr/local/hadoop
java -jar ./myapp/HDFSExample.jar

无法正常运行出现No FileSystem for scheme: hdfs错误。

解决方法:要能正确读取HDFS文件,程序就需要知道Hadoop集群的配置信息,如果你不是用“hadoop jar”命令来运行你的程序,

而是用“java”命令来运行的(例如 java com.codelast.MyProgramme),那么,程序就需要引入Hadoop集群的配置信息。

Hadoop集群的配置保存在 core-site.xml 和 hdfs-site.xml 两个文件中,所以在打包的时候要把它们打到jar包里的根目录下。

cp /usr/local/hadoop/etc/hadoop/core-site.xml ~/workspace/WordCount/src
cp /usr/local/hadoop/etc/hadoop/hdfs-site.xml ~/workspace/WordCount/src

通过上面的命令将core-site.xml 和 hdfs-site.xml复制到jar包里的根目录下后第二种java命令也正常运行

参考博文:http://www.codelast.com/

原文地址:https://www.cnblogs.com/fuheishi/p/11370330.html