Hadoop实现了一套Java 的FileSystem API,通过这套API,可以像操作本地文件一样,操作HDFS上面的文件和目录,并且可以和本地File进行交互,实现文件或目录的上传下载
本例基于Hadoop 2.7.2
Maven 加入Hadoop client 依赖
org.apache.hadoop
hadoop-client
2.7.2
通常情况下,下载还是很顺利的,如果你人品不好,下载很慢,那你就把 hadoop 安装目录下面 share下的 *.jar,自行去掉重复的,-test的jar,-source,-example的jar 加入到你的lib路径中。我这maven下下来是68个jar
Java 操作
Configuration configuration = new Configuration();
//如果不手动配置,也可以在classpath 的core-site.xml中配置
configuration.set("fs.default.name", "hdfs://192.168.189.141:9000");
DistributedFileSystem dfs = (DistributedFileSystem) FileSystem.get(configuration);
DatanodeInfo[] dataNodeStats = dfs.getDataNodeStats();
String[] names = new String[dataNodeStats.length];
System.out.println("List of all the datanode in the HDFS cluster:");
for (int i = 0; i < names.length; i++) {
names[i] = dataNodeStats[i].getHostName();
System.out.println(names[i]);
}
System.out.println(dfs.getUri().toString());
//文件操作和本地一样,
dfs.copyFromLocalFile(new Path("D:/Spark/bin"), new Path("/copy/"));
//删除
dfs.delete(new Path("/copy"), true);
//创建目录
dfs.mkdirs(new Path("/test/aaa/bbb"));
//上传一个目录
dfs.copyToLocalFile(new Path("/user/hive/warehouse/logs"), new Path("D:/aaa/"));
//读取文件内容
InputStream ins = dfs.open(new Path("/logs/LICENSE.txt"));
System.out.println(IOUtils.toString(ins));
//写入一个文件(目录自动创建)
OutputStream os = dfs.create(new Path("/test/新建文本文档.txt"));
IOUtils.copy(new FileInputStream("D:/新建文本文档.txt"), os);
注意,上面关于文件系统类的引用接为hadoop的
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;