package com.czxy.demo02;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.net.URI;
public class hdfs01 {
// 实例化配置文件
static Configuration configuration=new Configuration();
// 打印指定目录下文件名
public static void listStatus() throws Exception{
// 实例化文件系统
FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.100.201:8020"), configuration);
// 获取指定路径下的所有文件
FileStatus[] statuses = fileSystem.listStatus(new Path("/"));
// 遍历打印
for (FileStatus status : statuses) {
System.out.println(status);
}
}
// 修改文件或目录名字
public static void rename()throws Exception {
// 实例化文件系统
FileSystem system = FileSystem.get(new URI("hdfs://192.168.100.201:8020"), configuration);
boolean b = system.rename(new Path("/aaa"), new Path("/bbb"));
String str=b?"修改成功":"修改失败";
System.out.println(str);
}
// 获取创建文件的时间
public static void GetTime()throws Exception {
FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.100.201:8020"), configuration);
// 调用方法获取单个指定路径文件
FileStatus status = fileSystem.getFileStatus(new Path("/aaa"));
long time = status.getModificationTime();
System.out.println(time);
}
// 删除文件或目录
public static void deletefile()throws Exception {
FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.100.201"), configuration);
boolean b = fileSystem.delete(new Path("/aaa"), true);
System.out.println("删除结果"+b);
}
// 添加文件 --同时写入数据
public static void AddFile()throws Exception {
FileSystem hdfs=FileSystem.get(new URI("hdfs://192.168.100.201:8020"),configuration);
byte[] buff="hello word".getBytes();
// 创建文件用create 创建目录mkdir
FSDataOutputStream outputStream = hdfs.create(new Path("/aaa/b.txt"));
// 写入的数据 0,写入数据多少
outputStream.write(buff,0,buff.length);
outputStream.close();
}
// 从本地上传文件到linux中
public static void put() throws Exception {
FileSystem hdfs=FileSystem.get(new URI("hdfs://192.168.100.201:8020"),configuration);
// 移动数据move
// hdfs.moveFromLocalFile();
// 复制数据copy
hdfs.copyFromLocalFile(new Path("C:\\a"),new Path("/aaa/"));
}
// 查看文件是否存在
public static void check() throws Exception {
FileSystem hdfs=FileSystem.get(new URI("hdfs://192.168.100.201:8020"),configuration);
// 查看文件是否存在用exists
boolean b = hdfs.exists(new Path("/aaa"));
System.out.println("文件存在结果"+b);
}
//调用方法执行
public static void main(String[] args) throws Exception {
//获取指定路径所有文件
// listStatus();
//重命名
// rename();
//获取文件日期
// GetTime();
// //创建文件夹
// mkdir ();
// //删除文件
// deletefile();
// //创建数据
// AddFile();
// //上传数据
// put();
// //检查目录是否存在
check();
}
}