上一节课我们熟悉了HDFS的命令行操作,接下来我们将通过java代码访问HDFS服务。
1 系统、软件以及前提约束
2 操作
1 在eclipse中创建一个项目,加入下载好的jar包并设置到环境变量
2 将hadoop2.7.2.zip解压到C:\hadoop2.7.2目录下
3 写入以下的测试类
package net.wanho.hdfs;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class HDFSTest01 {
//在HDFS中创建一个文件夹
public static boolean CreatDir(String dst, Configuration conf) {
Path dstPath = new Path(dst);
try {
FileSystem dhfs = FileSystem.get(conf);
dhfs.mkdirs(dstPath);
} catch (IOException ie) {
ie.printStackTrace();
return false;
}
return true;
}
//上传一个本地文件到HDFS
public static boolean putToHDFS(String src, String dst, Configuration conf) {
Path dstPath = new Path(dst);
try {
FileSystem hdfs = dstPath.getFileSystem(conf);
hdfs.copyFromLocalFile(false, new Path(src), dstPath);
} catch (IOException ie) {
ie.printStackTrace();
return false;
}
return true;
}
//从HDFS中下载一个文件到本地
public static boolean getFromHDFS(String src, String dst, Configuration conf) {
Path dstPath = new Path(dst);
try {
FileSystem dhfs = dstPath.getFileSystem(conf);
dhfs.copyToLocalFile(false, new Path(src), dstPath);
} catch (IOException ie) {
ie.printStackTrace();
return false;
}
return true;
}
//删除HDFS中已经存在的一个文件
public static boolean checkAndDel(final String path, Configuration conf) {
Path dstPath = new Path(path);
try {
FileSystem dhfs = dstPath.getFileSystem(conf);
if (dhfs.exists(dstPath)) {
dhfs.delete(dstPath, true);
} else {
return false;
}
} catch (IOException ie) {
ie.printStackTrace();
return false;
}
return true;
}
/**
* 主函数测试
*/
public static void main(String[] args) {
boolean status = false;
Configuration conf = new Configuration();
System.setProperty("hadoop.home.dir", "C:\\hadoop2.7.2");
//192.168.100.192是作者的HDFS所在的linux地址,请读者根据实际情况修改
conf.set("fs.default.name", "hdfs://192.168.100.192:9000");
//192.168.100.192是作者的HDFS所在的linux地址,请读者根据实际情况修改
String dst1 = "hdfs://192.168.100.192:9000/wanhe";
status = CreatDir(dst1, conf);
System.out.println("status=" + status);
// 上传文件
// String dst = "hdfs://192.168.100.192:9000/wanhe";
// //请确保地址文件地址正确
// String src = "C:\\Users\\zhangli\\Desktop\\123.txt";
// status = putToHDFS(src, dst, conf);
// System.out.println("status=" + status);
// 获取文件
// String src = "hdfs://192.168.100.192:9000/wanhe";
// //请确保地址文件地址正确
// String dst = "C:\\Users\\zhangli\\Desktop";
// status = getFromHDFS(src, dst, conf);
// System.out.println("status=" + status);
// 删除文件
// dst = "hdfs://192.168.100.131:9000/wanhe/123.txt";
// status = checkAndDel(dst, conf);
// System.out.println("status=" + status);
}
}
至此,我们熟悉了通过java代码对hdfs进行增删改查的操作。