HDFS JAVA API介绍

时间:2025-02-13 16:04:27

注:在工程pom.xml 所在目录,cmd中运行 mvn package ,打包可能会有两个jar,名字较长的是包含所有依赖的重量级的jar,可以在linux中使用 java -cp 命令来跑。名字较短的jar,只包含了我们自己创建的类的依赖的轻量级jar,需要hadoop,所以在linux中需要使用 hadoop 命令来跑。

总之,

java -cp 来运行包含所有依赖的 jar

hadoop jar 来运行只包含我们创建的类的 jar

package org.training.hadoop.hdfs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path; public class HdfsExample { public static void testMkdirPath(String path) throws Exception {
FileSystem fs = null;
try {
System.out.println("Creating " + path + " on hdfs...");
Configuration conf = new Configuration();
// First create a new directory with mkdirs
Path myPath = new Path(path);
fs = myPath.getFileSystem(conf); fs.mkdirs(myPath);
System.out.println("Create " + path + " on hdfs successfully.");
} catch (Exception e) {
System.out.println("Exception:" + e);
} finally {
if(fs != null)
fs.close();
}
} public static void testDeletePath(String path) throws Exception {
FileSystem fs = null;
try {
System.out.println("Deleting " + path + " on hdfs...");
Configuration conf = new Configuration();
Path myPath = new Path(path);
fs = myPath.getFileSystem(conf); fs.delete(myPath, true);
System.out.println("Deleting " + path + " on hdfs successfully.");
} catch (Exception e) {
System.out.println("Exception:" + e);
} finally {
if(fs != null)
fs.close();
}
} public static void main(String[] args) {
try {
//String path = "hdfs:namenodehost:8020/test/mkdirs-test";
String path = "/test/mkdirs-test";
testMkdirPath(path);
//testDeletePath(path);
} catch (Exception e) {
System.out.println("Exceptions:" + e);
}
System.out.println("timestamp:" + System.currentTimeMillis());
}
}

打完包,在linux 中,使用命令

hadoop jar jar包 运行的类所在的包名.运行的类的类名

来执行。

如:

hadoop jar aurahadoop-0.1.0-SNAPSHOT.jar org.training.hadoop.hdfs.HdfsExample

执行 hadoop fs -ls /test 可以看到,/test/mkdirs-test 文件夹已经生成