在Windows系统上对hfds中的文件进行操作

在 linux 上我们可以通过命令对 hdfs 中的文件及文件目录进行处理,但是在 Windows 上编写代码时需要用到 hdfs 时该如何处理呢?其实 hdfs 也是可以部署在 Windows 系统上的,但是考虑到稳定性一般通常是部署在 linux 系统上,同时由于 hadoop2 和   hadoop3 的版本不同,导致其自身的功能上有些不同,其中 hadoop2 无法直接在页面上进行对文件的创建和删除等操作,但是hadoop3 可以直接操作。有关更多 hadoop 的内容,可以见 https://blog.csdn.net/qq_39187675/article/details/101557718

在 Windows 系统中,我们可以通过编写 java 代码来对hdfs中的文件进行操作。在写代码之前,需要导入有关 hadoop 的 jar 包才能完成相关操作,其中 jar 包的链接在下方。如果 linux 系统是在虚拟机上安装的,在运行代码是需要将虚拟网络打开,不然的话是连接不上 linux 上的 hadoop 的。

链接:https://pan.baidu.com/s/1U0TwbIvYS3jl_na86iPW9g 
提取码:th4u 

其实对 hdfs 的操作,无非就是上传、下载、读取文件内容等操作, 这篇文章只是单独编写一个类来完成对这些操作,常用来上传文件和下载文件,对于读取 hdfs 目录文件中的内容更多的是在 MapReduce 中进行的,在这里就不多叙述,在后面的文章中会进行详细介绍。下面的代码其实不止可以对 linux 上的 hdfs 进行操作,同时也可以对 Windows 上的进行操作,改一下IP地址就好了。

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class HDFSAPI {
    public static void main(String[] args) throws IOException {
        Configuration configuration = new Configuration ();   //在选择Configuration的时候要注意不要选错,在这里要选择hadoop相关的那个,其他的也是如此
        configuration.set ("fs.defaultFS", "hdfs://192.168.2.56:9000");  //这是linux系统的IP地址,端口号都是9000
        configuration.set ("dfs.replication", "1");
        configuration.set("fs.hdfs.impl","org.apache.hadoop.hdfs.DistributedFileSystem");
        configuration.set("fs.file.impl", "org.apache.hadoop.fs.LocalFileSystem");
        FileSystem fileSystem = FileSystem.get (configuration);
        Path path = new Path ("/hdfsdemo");  
        if (!fileSystem.isDirectory (path)) {   //判断是否已存在目录
            fileSystem.mkdirs (path);    //创建目录
        }
        fileSystem.copyFromLocalFile (new Path ("E:\\data\\test1.txt"), new Path ("hdfs://192.168.13.151:9000/hdfsdemo"));    //上传本地文件到hdfs中
        fileSystem.copyToLocalFile (new Path ("/hdfsdemo/test1.txt"), new Path ("E:\\data\\t.txt"));    //从hdfs中下载文件到本地
        FileStatus[] fileStatuses = fileSystem.listStatus (new Path ("/hdfsdemo"));  //文件的状态
        for(FileStatus item:fileStatuses){
            System.out.println (item);
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值