本篇讲解如何通过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

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

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

  1. hadoop学习笔记(十):hdfs在命令行的基本操作命令(包括文件的上传和下载和hdfs中的文件的查看等)

    hdfs命令行 ()查看帮助 hdfs dfs -help ()查看当前目录信息 hdfs dfs -ls / ()上传文件 hdfs dfs -put /本地路径 /hdfs路径 ()剪切文件 hd ...

  2. 通过JAVA对FTP服务器连接,上传,下载,读取,移动文件等

    记录一次对FTP服务器文件内容 通过Java程序对FTP服务器文件处理:连接,上传,下载,读取,移动文件等. 需求描述:今天接到一个任务,在Java项目中,读取FTP服务器上的一些文件,进行一些业务操 ...

  3. drupal7 开发自定义上传、下载模块的上传功能

    关键点有两个:1.在页面上显示出上传的控件,2.代码实现文件上传到服务器的功能 一.显示控件: 先来看关键点1: 实现页面显示出上传控件, 关键代码: $form['my_file_field'] = ...

  4. java上传并下载以及解压zip文件有时会报文件被损坏错误分析以及解决

    情景描述: 1.将本地数据备份成zip文件: 2.将备份的zip文件通过sftp上传到文件服务器: 3.将文件服务器上的zip文件下载到运行服务器: 4.将下载的zip文件解压到本地(文件大小超过50 ...

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

    对于HTML5已经支持AJAX文件上传了,但如果需要兼容的话还是得用一点小技巧的,HTML5等等介绍,先来看看以前我们是怎么写的. 网上可能会有一些叫AJAX文件上传插件,但在AJAX2.0之前是不可 ...

  6. Nancy之文件上传与下载

    零.前言 由于前段时间一直在找工作,找到工作后又比较忙,又加班又通宵的赶项目,所以博客有段时间没有更新了. 今天稍微空闲一点,碰巧前几天看到有园友问我Nancy中下载文件的问题,然后就趁着休息的时间写 ...

  7. SpringBoot下文件上传与下载的实现

    原文:http://blog.csdn.net/colton_null/article/details/76696674 SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传 ...

  8. 基于hap的文件上传和下载

    序言 现在,绝大部分的应用程序在很多的情况下都需要使用到文件上传与下载的功能,在本文中结合hap利用spirng mvc实现文件的上传和下载,包括上传下载图片.上传下载文档.前端所使用的技术不限,本文 ...

  9. HDFS的上传与下载(put & get)

    最近在做一个小任务,将一个CDH平台中Hive的部分数据同步到另一个平台中.毕竟我也刚开始工作,在正式开始做之前,首先进行了一段时间的练习,下面的内容就是练习时写的文档中的内容.如果哪里有错误或者疏漏 ...

随机推荐

  1. MySQL 8.0.13 下载安装教程

    MySQL是使用最多的数据库,自己电脑上肯定要装一个来多加学习,自己搞不懂的一些东西要多写一些 sql 语句练习. 首先去 mysql 官网下载,地址:https://dev.mysql.com/do ...

  2. NoSQL、memcached介绍、安装memcached、查看memcached状态

    1.NoSQL 2.memcached介绍     3.安装memcached(二进制包安装) yum install -y memcached libmemcached libevent (若没有安 ...

  3. (转)用JS获取地址栏参数的方法(超级简单)

    转自http://www.cnblogs.com/fishtreeyu/archive/2011/02/27/1966178.html 用JS获取地址栏参数的方法(超级简单) 方法一:采用正则表达式获 ...

  4. sklearn learn preprocessing

    train_test_split sklearn.model_selection.train_test_split(*arrays, test_size(float,int/None),#defaul ...

  5. JTA事务管理

    何为分布式事务 一个事务包含多个操作,多个操作操作了多个数据源,这样的事务称为分布式事务 和普通事务的区别 单一数据源,事务管理可以借助数据源本地事务完成,实现简单 分布式事务之困难:不可简单的借助数 ...

  6. windows下配置下burpsuite的小方法。

    1.下载破解版burpsuite和正版burpsuite. 2.安装正版burpsuite(免费版) 3.打开安装路径 4.把破解版的burp拷贝到安装路径下 5.该路径下应该有个burpsuite_ ...

  7. Linux第九节课学习笔记

    fdisk可添加.删除.转换分区. 创建主分区:n-p-w:扩展分区:n-e:逻辑分区:n-l. SWAP分区专用格式化命令mkswap,专用挂载命令swapon. 磁盘容量配额中,硬限制必须,软限制 ...

  8. Spark参数详解 一(Spark1.6)

    Spark参数详解 (Spark1.6) 参考文档:Spark官网 在Spark的web UI在"Environment"选项卡中列出Spark属性.这是一个很有用的地方,可以检查 ...

  9. Rocketlab公司火箭Electron介绍

    http://https://en.wikipedia.org/wiki/Rocket_Lab https://www.rocketlabusa.com/ Rocketlab(火箭实验室)是一家致力于 ...

  10. The Best Books on Game Dev

    https://www.goodreads.com/list/show/99288.The_Best_Books_on_Game_Dev