起因
在使用api“public void copyToLocalFile(boolean delSrc, Path src, Path dst)”对文件进行操作的时候出现以下异常。
异常栈如下
Exception in thread "main" java.lang.NullPointerException
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1012)
at org.apache.hadoop.util.Shell.runCommand(Shell.java:482)
at org.apache.hadoop.util.Shell.run(Shell.java:455)
at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:715)
at org.apache.hadoop.util.Shell.execCommand(Shell.java:808)
at org.apache.hadoop.util.Shell.execCommand(Shell.java:791)
at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:659)
at org.apache.hadoop.fs.FilterFileSystem.setPermission(FilterFileSystem.java:490)
at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:462)
at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:428)
at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:908)
at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:889)
at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:786)
at org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:365)
at org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:338)
at org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:289)
at org.apache.hadoop.fs.FileSystem.copyToLocalFile(FileSystem.java:1970)
at org.apache.hadoop.fs.FileSystem.copyToLocalFile(FileSystem.java:1939)
at org.apache.hadoop.fs.FileSystem.copyToLocalFile(FileSystem.java:1915)
at cn.mytest.hdfs.TestHDFS.main(TestHDFS.java:30)
错误原因
hadoop要与windows打交道,需要通过和windows的相关的类库进行交互操作文件。而本地不存在hadoop交互的类库。
解决办法
1、windows本地编译hadoop,并设置HADOOP_HOME环境变量
2、通过java操作
使用public void copyToLocalFile(boolean delSrc, Path src, Path dst, boolean useRawLocalFileSystem)API
1)第一个参数代表是否删除源文件
2)最后一个参数代表是否使用本地的文件系统(java的文件系统)
代码示例如下
public class TestHDFS {
public static void main(String[] args) throws IOException {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://myServer1:9000");
FileSystem fileSystem = FileSystem.get(conf);
RemoteIterator<LocatedFileStatus> listFiles = fileSystem.listFiles(new Path("/"), false);
while(listFiles.hasNext()){
LocatedFileStatus fileStatus = listFiles.next();
Path path = fileStatus.getPath();
String name = path.getName();
System.out.println(name);
}
//fileSystem.copyToLocalFile(new Path("/hello.txt"),new Path("F://"));
fileSystem.copyToLocalFile(false,new Path("/hello.txt"),new Path("F://"),true);
fileSystem.close();
}
}
---------------------------------------------------------------------------------------------------------------------------------------
如果对您有帮助,欢迎打赏,您的认可是我继续前进的动力!