Eclipse 上传 删除 下载 分析 hdfs 上的文件

本篇讲解如何通过Eclipse 编写代码去操作分析hdfs 上的文件。

1、在eclipse 下新建Map/Reduce Project项目。如图: 
 
项目建好后,会默认加载一系列相应的jar包。 
下面还有很多包。 
2、我们新建Java 类就可以了。代码如下:

package org.hadoop.examples;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FSDataInputStream;
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 org.apache.hadoop.io.IOUtils;

public class operateHdfs {

    public static void main(String args[]) {
        // 测试 创建新文件
        String contents = "hello world 张三\n--created by lyf\n";

        // 创建文件夹
        // creatFolder("/input/lyf2/");
        // 创建文件
        // createFile("/input/demo.txt", contents);
        // 删除文件(文件和文件夹)
        // deleteFile("/input/first.txt");
        // deleteFile("/input/lyf22");
        // 上传文件到指定位置
        // uploadFile("E:/myTest.txt", "/input");
        // 重命名(文件和文件夹--文件夹下不含文件)
        // renameFile(new Path("/input/lyf"),new Path("/input/test"));
        // 获取指定路径下的所有文件
        // getUnderDirAllFile("/input/lyf");
        // 判断文件是否存在
        // findFileIsExit(new Path("/input/lyf/first.txt"));
        // 查看某个文件在HDFS集群的位置
        // findLocationOnHadoop(new Path("/input/lyf/demo.txt"));
        // 文件内容追加
        // appendFile("/input/demo.txt", "/input/demo.txt");
        // 读取指定文件
        // readFile("/input/demo.txt");
        // 写入文件 和创建文件一样
        // writeFile("/input/demo.txt");
        // 下载文件
        // downloadFile(new Path("/input/demo.txt"),new Path("D:/demo222.txt"));

    }

    // 创建文件目录
    public static void creatFolder(String folderPath) {

        // master
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://192.168.1.216:9000");

        Path demoDir = new Path(folderPath);
        try {
            FileSystem fs = FileSystem.get(conf);
            if (fs.mkdirs(demoDir)) {
                System.out.println("文件夹创建成功!");
            } else {
                System.out.println("文件夹创建失败!");
            }
        } catch (IOException e) {
            System.out.println("出现异常!");
        }
    }

    // 创建新文件(直接生成指定路径下的first.txt,即:/eclipse/first.txt)
    public static void createFile(String dst, String contents) {
        // master
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://192.168.1.216:9000");
        System.out.println("-----------:" + conf);
        try {
            FileSystem fs = FileSystem.get(conf);

            Path dstPath = new Path(dst); // 目标路径
            // 打开一个输出流
            FSDataOutputStream outputStream = fs.create(dstPath);

            outputStream.write(contents.getBytes());
            outputStream.writeUTF(contents);

            outputStream.close();
            fs.close();
            System.out.println("文件创建成功!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("出现异常----文件创建失败!");
        }
    }

    // 删除指定文件
    public static void deleteFile(String file) {

        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://192.168.1.216:9000");
        FileSystem fs;
        try {
            fs = FileSystem.get(conf);
            Path path = new Path(file);
            fs.delete(path);
            fs.close();
            System.out.println("文件删除成功" + conf);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("出现异常---文件删除失败" + conf);
        }

    }

    // 上传指定文件到指定路径
    public static void uploadFile(String s, String d) {

        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://192.168.1.216:9000");
        FileSystem fs;
        try {
            fs = FileSystem.get(conf);
            Path src = new Path(s);
            Path dst = new Path(d);
            fs.copyFromLocalFile(src, dst);
            fs.close();
            System.out.print("文件上传成功!" + conf);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.print("异常---文件上传失败!" + conf);
        }
    }

    // 获取指定路径下的所有文件
    public static void getUnderDirAllFile(String rootPath) {
        Path targetDir = new Path(rootPath);
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "192.168.1.216:9000");

        try {
            FileSystem fs = FileSystem.get(conf);
            FileStatus[] fileStatus = fs.listStatus(targetDir);
            for (FileStatus file : fileStatus) {
                System.out.println(file.getPath() + "--" + file.getGroup() + "--" + file.getBlockSize() + "--"
                        + file.getLen() + "--" + file.getModificationTime() + "--" + file.getOwner());
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("异常----文件获取失败!");
        }
    }

    // 判断文件是否存在
    public static void findFileIsExit(Path filePath) {
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://192.168.1.216:9000");
        try {
            FileSystem fs = FileSystem.get(conf);
            if (fs.exists(filePath)) {
                System.out.println("文件存在!");
            } else {
                System.out.println("文件不存在!");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("出现异常!");
        }

    }

    // 读取指定路径的文件
    public static void readFile(String path) {
        Configuration conf = new Configuration();
        //conf.set("fs.defaultFS", "hdfs://192.168.1.216:9000");
        try {
            FileSystem fs = FileSystem.get(URI.create("hdfs://192.168.1.216:9000"),conf);
            FSDataInputStream ins = fs.open(new Path(path));
            // readUTF 读取的文件必须是writeUTF 写入的,否则报  EOFException
            String content = ins.readUTF();
            System.out.println("文件内容" + content);
            ins.close();
            // fs.close();

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取内容失败!");
        }
    }

    // 写如文件
    public static void writeFile(String path) {
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://192.168.1.216:9000");
        try {
            FileSystem fs = FileSystem.get(conf);
            FSDataOutputStream ous = fs.create(new Path(path));
            ous.writeUTF("欢迎写入文件!");
            ous.close();
            System.out.println("文件写入成功!");

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件写入失败!");
        }
    }

    // 追加内容到
    public static void appendFile(String filePath, String addPath) {
        Configuration conf = new Configuration();
        conf.set("fs.defaultSF", "hdfs://192.168.1.216:9000");

        conf.setBoolean("dfs.support.append", true);
        try {
            FileSystem fs = FileSystem.get(URI.create(filePath), conf);
            // 要追加的文件流,inpath为文件
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));
            OutputStream out = fs.append(new Path(addPath));
            IOUtils.copyBytes(in, out, 4096, true);

            System.out.println(" 文件追加成功!" + conf);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("出现异常---文件追加失败!" + conf);
        }
    }

    // 文件重命名(指定文件改成指定名称)
    public static void renameFile(Path oldName, Path newName) {
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://192.168.1.216:9000");
        try {
            FileSystem fs = FileSystem.get(conf);
            if (fs.rename(oldName, newName)) {
                System.out.println("文件重命名---成功!");
            } else {
                System.out.println("文件重命名---失败!");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("异常----文件重命名---失败!");
        }
    }

    // 查看某个文件在HDFS集群的位置
    public static void findLocationOnHadoop(Path rootPath) {

        Configuration conf = new Configuration();
        // conf.set("fs.defultFS", "hdfs://192.168.1.216:9000");

        try {
            FileSystem fs = FileSystem.get(URI.create("hdfs://192.168.1.216:9000"), conf);
            FileStatus fileStaus = fs.getFileStatus(rootPath);
            BlockLocation[] bloLocations = fs.getFileBlockLocations(fileStaus, 0, fileStaus.getLen());
            for (int i = 0; i < bloLocations.length; i++) {
                System.out.println("block_" + i + "_location:" + bloLocations[i].getHosts()[0]);
            }
            System.out.println("获取文件在HDFS集群位置成功!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("异常 ----获取文件在HDFS集群位置失败!");
        }

    }

    // 下载文件到指定位置
    public static void downloadFile(Path filePath,Path downPath){
        Configuration conf = new Configuration();

        try {
            FileSystem fs = FileSystem.get(URI.create("hdfs://192.168.1.216:9000"),conf);
            fs.copyToLocalFile(filePath, downPath);
            System.out.println("文件下载成功!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("----异常--- 文件下载失败!");
        }
    }
}

其中hdfs://192.168.1.216 是HDFS文件服务器的地址,你改成你文件服务地址就好了。

这时候是已经可以运行了,但控制台会显示如下错误:

log4j:WARN No appenders could be found for logger (org.apache.Hadoop.metrics2.lib.MutableMetricsFactory). 
log4j:WARN Please initialize the log4j system properly. 
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

解决方式:在src 文件下新建 log4j.properties 文件里面的内容如下:

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

至此文件操作就已经完成了。

时间: 2024-07-30 13:38:54

Eclipse 上传 删除 下载 分析 hdfs 上的文件的相关文章

AJAX文件上传实践与分析,带HTML5文件上传API。

对于HTML5已经支持AJAX文件上传了,但如果需要兼容的话还是得用一点小技巧的,HTML5等等介绍,先来看看以前我们是怎么写的. 网上可能会有一些叫AJAX文件上传插件,但在AJAX2.0之前是不可能实现的,因为浏览器的原因,AJAX根本获取不了文件信息,当然这里并不是说就不能文件上传了,只是说在AJAX2.0之前所谓的AJAX文件上传都是假冒的,核心更本没有用AJAX,而是利用iframe实现的,下面我们来看看如何利用iframe实现页面无刷新上传文件. iframe无刷新上传文件版. ht

文件上传和下载--详解实现

 1.文件上传和下载分析 文件上传: 就是将客户端的数据发送到服务器上 文件上传要求:            浏览器端要求:                                    1.表单提交方式 post                                    2.提供文件上传框(组件) input type="file"                                    3.表单entype属性必须为 multipart/form-

基于asp.net 的文件上传和下载~~~转

基于asp.net 的文件上传和下载 摘要: 文件的上传和下载是网络中非常重要的两种应用, 本文介绍了使用asp.net 控件实现文件上传的基本方法.解决了当上传大文件时出现各种问题, 并给出了几种解决方案和技巧.另外, 下载文件用二进制读写的方式实现. 1 引言          文件的上传和下载是网络中非常重要的两种应用.其实现方法主要有FTP 方式和HTTP 方式两种, FTP( File Transfer Protocol)是指文件传输协议, 主要用来在网络上传输文件.这种方式虽说文件传

Nancy之文件上传与下载

零.前言 由于前段时间一直在找工作,找到工作后又比较忙,又加班又通宵的赶项目,所以博客有段时间没有更新了. 今天稍微空闲一点,碰巧前几天看到有园友问我Nancy中下载文件的问题,然后就趁着休息的时间写下了这篇博客. 直接进正题吧! 一.新建一个空的asp.net应用程序 通过nuget安装相应的packages 二.添加Modules和Views文件夹 用于存放我们的“控制器”和视图(这一步不是必须的喔!) 三.新建CustomRootPathProvider.cs 具体如下: 1 public

基于hap的文件上传和下载

序言 现在,绝大部分的应用程序在很多的情况下都需要使用到文件上传与下载的功能,在本文中结合hap利用spirng mvc实现文件的上传和下载,包括上传下载图片.上传下载文档.前端所使用的技术不限,本文重点在于后端代码的实现.希望可以跟随我的一步步实践,最终轻松掌握在hap中的文件上传和下载的具体实现. 案例 1.  数据库设计 表结构 SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for

vsftpd开启日志记录上传、下载、删除,分析xferlog日志

在web服务器上搭建了vsftpd用来上传代码程序,开启日志记录客户端的上传.下载删除等操作: #修改/etc/vsftpd/vsftpd.conf [[email protected] ~]# vim /etc/vsftpd/vsftpd.conf anonymous_enable=NO anon_root=/ftpanon local_enable=YES write_enable=YES local_umask=022 dirmessage_enable=YES dual_log_enab

C#实现FTP文件的上传、下载功能、新建目录以及文件的删除

本来这篇博文应该在上周就完成的,可无奈,最近工作比较忙,没有时间写,所以推迟到了今天.可悲的是,今天也没有太多的时间,所以决定给大家贴出源码,不做详细的分析说明,如果有不懂的,可以给我留言,我们共同讨论. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using Sys

webDAV服务的开启以及客户端的上传、下载、删除、新建文件夾、列表的代码(C#)

windows server 2003开启webDAV服务 1. 启动“IIS管理器”选择“WEB服务扩展”,选择“WEBDAV”的允许按钮启动WEBDAV功能 2.建立一个虚拟目录,对应到一个本地目录. 3.启动系统“服务”中的“WebClient”服务 参考网址 WebDAV文档rfc2518    http://www.ietf.org/rfc/rfc2518.txt webdav常用方法和概念总结   http://blog.csdn.net/mahongming/archive/200

vsftp实现只能上传不能下载、删除权限配置

vsftpd可以对每个用户特别限制.只要给那个用户建立一个设置文件,然后在文件里设置 在vsftpd.conf里加user_config_dir=/etc/vsftpd/vsftpd_user_conf,这是文件夹.当然你可以自己选把用户文件放在哪在此文件夹里新建一个文件,跟用户名相同.VSFTPD会比对用户名和用户设置文件. 在文件里加local_root=PATH to directory就可以更改用户的home directorylocal_max_rate=XXXX就可以限制此用户的带宽