问题描述:
在将本地文件上传到HDFS时出错。上传的代码如下:
public static void writeToHdfs() throws Exception{
//String hdfsPath = "hdfs://master:8020/test1/test.txt";//hdfs位置
String localPath = "D:\\test.txt";//本地磁盘位置
Configuration configuration = new Configuration();
//configuration.set("fs.defaultFS", "hdfs://10.10.2.101:9000");
FileSystem fs = FileSystem.get(new URI("hdfs://master:8020"), configuration);
FSDataOutputStream out = fs.create(new Path("/test/test.txt"));//创建一个输出流
InputStream in = new FileInputStream(new File(localPath));//从本地读取文件
IOUtils.copyBytes(in, out, 100, true);
System.out.println("上传over");
}
{
如果将hdfs的地址和端口写错,还会出现下面的报错信息:
(注意要和core-site.xml中的fs.defaultFS的value一致)
RPC response exceeds maximum data length; Host Details : local host is: "DESKTOP-40GENV7/2.0.1.21"; destination host is: "master":9000;
}
出现的错误:
使用指令"sudo -u hdfs hdfs dfs -ls /"查看文件夹的权限看到如下结果
可以看出test文件夹的所有者是hdfs,hdfs相当于一个超级用户,
解决方案1:
使用指令"sudo -u hdfs hadoop fs -chown root /test",把test文件夹的用户改成root(或者自己的用户名)。
另外还需要指令"sudo -u hdfs hdfs dfs -chmod 777 /test",开放文件夹的读写权限。
参考:https://blog.youkuaiyun.com/g11d111/article/details/72902112
https://blog.youkuaiyun.com/wzygis/article/details/46966235
解决方案2:
从代码入手,将代码修改成:
FileSystem fs = FileSystem.get(new URI("hdfs://master:8020"), configuration,"hdfs");
在FileSystem.get()函数里添加上user:"hdfs"。搞定,不用像方案1里去修改权限了