java hdfs kerberos_java操作HDFS相关demo(TDH,kerberos认证)

public class Test {

private static Configuration conf;

private static FileSystem fs;

//开启kerberos认证

static {

System.setProperty("java.security.krb5.conf", "D:\\HDFS-test\\krb5.conf");

conf=new Configuration();

conf.addResource(new Path("D:\\HDFS-test\\hdfs-site.xml"));

conf.set("hadoop.security.authentication", "kerberos"); //配置认证方式

conf.set("fs.default.name", "hdfs://172.20.237.112:8020");//namenode的地址和端口

UserGroupInformation.setConfiguration(conf);

try {

UserGroupInformation.loginUserFromKeytab("hdfs/gz237-112", "D:\\HDFS-test\\hdfs.keytab");

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 未开启安全

*/

// static {

//      conf = new Configuration();

//      ip为Namenode master所在节点

//      conf.set("fs.default.name", "hdfs://172.20.237.112:8020");

//       FileSystem类在hadoop-hdfs包中

//       conf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());

// }

public static void main(String[] args) throws Exception {

// mkdirCatalog("/yfb");//在hdfs上创建目录

putfile("D:\\test.txt", "/yfb");//上传文件

// createFile("/data.txt");//在hdfs上创建文件

// deleteFile("/data.txt");//删除HDFS上的文件

// downloadFile("/dddd1111.txt","D:\\");//文件下载

}

//1、创建目录

public static void mkdirCatalog(String path) throws Exception{

//创建连接,使用开源的进行,连接报错

Caused by: java.net.ConnectException: Connection refused: no further information

at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)

at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)

at org.apache.hadoop.net.SocketIOWithTimeout.connect(SocketIOWithTimeout.java:206)

// FileSystem fs = FileSystem.get(URI.create("hdfs://172.20.237.112:9000"),conf);

//TDH的方式

fs = FileSystem.get(conf);

fs.mkdirs(new Path(path));

}

//上传文件到hdfs

public static void putfile(String localfile,String hdfsfile) throws IOException {

fs = FileSystem.get(conf);

fs.copyFromLocalFile(new Path(localfile),new Path(hdfsfile));

}

//HDFS上创建文件

public static void createFile(String path) throws Exception {

fs = FileSystem.get(conf);

fs.createNewFile(new Path(path));

}

//删除HDFS上的文件

public static void deleteFile(String path) throws Exception {

fs = FileSystem.get(conf);

if(fs.exists(new Path(path))){

fs.delete(new Path(path),true);

}else {

System.out.println("您所删除的文件不存在!");

}

}

//下载文件到本地

public static void downloadFile(String hdfsPath,String localPath) throws Exception {

fs = FileSystem.get(conf);

fs.copyToLocalFile(new Path(hdfsPath),new Path(localPath));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值