(四)Eclipse下javaAPI操作HDFS

在操作之前先要做好准备工作。

Configuration configuration = new Configuration();
FileSystem fileSystem = FileSystem.get(configuration);
操作名称操作位置代码
1、新建文件夹命令行hadoop fs -mkdir /newDir
EclipsefileSystem.mkdirs(new Path(“/newDir”));
2、删除文件/夹命令行hadoop fs -rm/r /newDir
EclipsefileSystem.delete(new Path(“/newDir”));
3、存在文件/夹命令行hadoop fs -test -e /user >>echo$? 0存在1不存在
EclipsefileSystem.exists(new Path(“/file”));

Demo1

public class myHdfs {
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        Configuration configuration = new Configuration();
        FileSystem fileSystem = FileSystem.get(configuration);
        if(fileSystem.exists(new Path("/newDir"))){
            System.out.println("already existing!I'll delete it");
            fileSystem.delete(new Path("/newDir"));

        }else
        {
            System.out.println("No existing!I'll create and delete it");
            fileSystem.mkdirs(new Path("/newDir"));
            fileSystem.delete(new Path("/newDir"));
        }
        fileSystem.close();
    }

}
操作名称操作位置代码
4、读取文件属性命令行hadoop fs -ls /
EclipsefileSystem.getFileStatus(new Path(“/”));

Demo2

public class myHdfsLs {
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        Configuration configuration = new Configuration();
        FileSystem fileSystem = FileSystem.get(configuration);
        FileStatus[] fStatus = fileSystem.listStatus(new Path("/"));
        for(FileStatus fileStatus:fStatus){
           System.out.println("文件路径:"+fileStatus.getPath());
           System.out.println("块的大小:"+fileStatus.getBlockSize());
           System.out.println("文件所有者:"+fileStatus.getOwner()+":"+fileStatus.getGroup());
           System.out.println("文件权限:"+fileStatus.getPermission());
           System.out.println("文件长度:"+fileStatus.getLen());
           System.out.println("备份数:"+fileStatus.getReplication());
           System.out.println("修改时间:"+fileStatus.getModificationTime());
        }
    }

}
操作名称操作位置代码
5、读取内容命令行hadoop fs -cat /hello
Eclipse采用输入输出流进行System.out进行显示
Eclipsefin.seek(num);//从第num个字节开始读取
6、获取属性EclipseFileStatus status=FileSystem.getFileStatus(new Path(url));

Demo3

public class myHdfsCat {
    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        FileSystem fileSystem;
        String url = "/hello";
        try {
            fileSystem = FileSystem.get(configuration);
            //读取文件内容,已知文件内容长度
            if(fileSystem.exists(new Path(url))) {
                FSDataInputStream fin = fileSystem.open(new Path(url));
                //fin.seek(2);//从第二个字节开始读取,汉字要注意在UTF-83个字节
                FileStatus status = fileSystem.getFileStatus(new Path(url));
                int len = Integer.parseInt(String.valueOf(status.getLen()));
                System.out.println("文件长度:"+len);
                byte[] b = new byte[len];
                fin.readFully(0,b);
                System.out.println(new String(b));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

7、创建文件/写入
命令行:由于hdfs是一次写入多次读取的文件管理系统,所以不支持在线对文件进行写,可以在本地写好后上传.
创建文件命令:hadoop fs -touchz /file
上传文件命令:hadoop fs -put /datafile
Eclipse:
FSDataOutputStream fout = fs.create(new Path("/newhello"));
fout.write("hello world".getBytes());

操作名称操作位置代码
8、复制文件命令行hadoop fs -cp /hello /h1
Eclipse如下

注:剪切可以先复制再删除源文件。
Demo4

public class myHdfsCopy {
    public static void main(String[] args) throws IOException {
        Configuration configuration = new Configuration();
        FileSystem fileSystem = FileSystem.get(configuration);
        //复制文件,需要使用
        FSDataInputStream fin = fileSystem.open(new Path("/hello"));
        FSDataOutputStream fout = fileSystem.create(new Path("/hellott"));
        IOUtils.copy(fin, fout);
    }
}
操作名称操作位置代码
9、上传命令行hadoop fs -put /hellott
Eclipse如下
10、下载命令行hadoop fs -get /h1
Eclipse如下

Demo5

public class myHdfsUpdateLoad {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(conf);
        //上传下载要注释其中一个,要保证先上传后下载
        //上传
        InputStream in = new FileInputStream("/root/myCode/testFile/hello");
        FSDataOutputStream fout = fs.create(new Path("/hello1"));
        IOUtils.copy(in, fout);

        //下载
        FSDataInputStream fin = fs.open(new Path("/hello1"));
        OutputStream out = new FileOutputStream("/root/myCode/testFile/hello1");
        IOUtils.copy(fin, out);
    }

}

11、 hadoop路径读取文件
http://blog.youkuaiyun.com/timliangl/article/details/78200165

Eclipse使用Java API操作HDFS可按以下步骤进行: ### 环境准备 - 下载Hadoop压缩包并解压到指定目录,如D盘根目录,可参考链接:https://pan.baidu.com/s/13312--jSuaUPWW-I6GWAJQ [^4]。 - 添加环境变量: - 变量名:`HADOOP_HOME`,变量值:`D:\hadoop\hadoop-common-2.2.0-bin-master` [^4]。 - 变量名:`HADOOP_USER_NAME`,变量值:`root` [^4]。 - 在`path`后加上`D:\hadoop\hadoop-common-2.2.0-bin-master\bin` [^4]。 - 将`plugin`文件夹放到Eclipse安装目录的`dropins`目录下,参考链接:https://pan.baidu.com/s/1x_bE9hYdUCOs4pvFy3XnVg [^4]。 ### 创建项目 - 新建MapReduce Project项目,项目名为`HdfsEx`,选择`Configure Hadoop install diredtory`,输入Hadoop安装目录`/usr/local/hadoop` [^2]。 - 在Eclipse工作界面左侧的“Package Explorer”面板中,找到创建好的工程名称(如`HDFSExample`),在该工程名称上点击鼠标右键,在弹出的菜单中选择“New->Class”菜单 [^1]。 ### 编写代码示例 以下是一个检测HDFS中是否存在一个文件的示例代码: ```java package com.hadoop.hdfs; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.junit.Test; public class HdfsClient { @Test public void testCheckFileExists() throws IOException, InterruptedException, URISyntaxException { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(new URI("hdfs://hadoop130:8020"), conf, "hadoop"); Path filePath = new Path("/your/file/path"); boolean exists = fs.exists(filePath); if (exists) { System.out.println("文件存在"); } else { System.out.println("文件不存在"); } fs.close(); } } ``` 上述代码参考了创建目录的代码结构,通过`FileSystem`的`exists`方法来检测文件是否存在 [^3]。 ### 可能遇到的问题及解决方案 - 若遇到Hadoop环境变量配置相关问题,有以下解决方案: - 第一种方案:安装配置Windows平台下的Hadoop,配置完成后必须重启电脑 [^5]。 - 第二种方案:将Linux上进行Hadoop安装的Hadoop压缩包下载并解压,然后在解压包`bin`目录下额外添加Windows相关依赖文件(`winutils.exe`、`winutils.pdb`、`hadoop.dll`),然后进行Hadoop环境变量配置,配置完成后必须重启电脑 [^5]。 - 第三种方案:使用`FileSystem`类自带的方法,即便不对Hadoop的环境变量配置也可正常实现代码功能,缺点是本地路径下没有附带一个`xxx.crc`的校验文件 [^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值