直接使用FileSystem 创建一个路径
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
@Test
public void test() throws IOException, URISyntaxException, InterruptedException {Configuration conf = new Configuration();// 配置在集群上运行conf.set("fs.defaultFS", "hdfs://hadoop102:9000");//1 获取hdfs客户端对象FileSystem fs = FileSystem.get(conf);//2 在hdfs上创建路径fs.mkdirs(new Path("/test"));//3 关闭资源IOUtils.closeStream(fs);
}
这样写是不能直接执行的,应为我当前用户是我这个电脑上的默认的用户,是没有权限在hdfs上创建文件的(除非我配置了)。
org.apache.hadoop.security.AccessControlException: Permission denied: user=yuanyu, access=WRITE, inode="/test2.txt":atguigu:supergroup:drwxr-xr-x
at org.apache.hadoop.hdfs.server.namenode.FSPermissionChecker.check(FSPermissionChecker.java:319)
at org.apache.hadoop.hdfs.server.namenode.FSPermissionChecker.check(FSPermissionChecker.java:292)
at org.apache.hadoop.hdfs.server.namenode.FSPermissionChecker.checkPermission(FSPermissionChecker.java:213)
at org.apache.hadoop.hdfs.server.namenode.FSPermissionChecker.checkPermission(FSPermissionChecker.java:190)
at org.apache.hadoop.hdfs.server.namenode.FSDirectory.checkPermission(FSDirectory.java:1720)
我们可以在运行的时候添加 -DHADOOP_USER_NAME=atguigu,修改所有者。
在Eclipse 中右键执行的时候选择 Run As -> Run Configurations... 创建一个新的Java Application,点击 Arguments,在VM arguments,添加 -DHADOOP_USER_NAME=atguigu 即可。
core-site.xml:
<!-- 指定HDFS中NameNode的地址 -->
<property><name>fs.defaultFS</name><value>hdfs://hadoop102:9000</value>
</property>
上面写法程序执行过于繁琐,可以简化
注意:
import java.net.URI;
@Test
public void test() throws IOException, URISyntaxException, InterruptedException {Configuration conf = new Configuration();// 配置在集群上运行//1 获取hdfs客户端对象FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"),conf,"atguigu");//2 在hdfs上创建路径fs.mkdirs(new Path("/test2"));//4 关闭资源IOUtils.closeStream(fs);
}
/**
* Get a filesystem instance based on the uri, the passed
* configuration and the user
* @param uri of the filesystem
* @param conf the configuration to use
* @param user to perform the get as
* @return the filesystem instance
* @throws IOException
* @throws InterruptedException
*/
public static FileSystem get(final URI uri, final Configuration conf,final String user) throws IOException, InterruptedException
通过URLStreamHandler实例以标准输出方式显示 Hadoop 文件系统的文件
@Test
public void test() throws Exception {URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());//每个 java 虚拟机只能调用一次这个方法String uri = "hdfs://hadoop102:9000/test.txt";InputStream in = new URL(uri).openStream();IOUtils.copyBytes(in, System.out, 4096, false);//中文会乱码
}
参考:https://blog.csdn.net/xinpiannanhai/article/details/80314657