工具类HdfsUtils.java,及测试用例代码如下:

HdfsUtils.java

  1. package com.xy6.demo.utils;

  2. import java.io.ByteArrayInputStream;

  3. import java.io.IOException;

  4. import java.io.InputStream;

  5. import java.io.OutputStream;

  6. import java.net.URI;

  7. import java.util.ArrayList;

  8. import java.util.List;

  9. import org.apache.commons.lang.StringUtils;

  10. import org.apache.hadoop.conf.Configuration;

  11. import org.apache.hadoop.fs.FSDataInputStream;

  12. import org.apache.hadoop.fs.FSDataOutputStream;

  13. import org.apache.hadoop.fs.FileStatus;

  14. import org.apache.hadoop.fs.FileSystem;

  15. import org.apache.hadoop.fs.Path;

  16. import org.apache.zookeeper.common.IOUtils;

  17. /**

  18. * operate hdfs file or directory util class

  19. *

  20. * @author zhang

  21. * @since 2016-09-26

  22. *

  23. */

  24. public class HdfsUtils {

  25. public static String uri = "hdfs://192.168.1.118:9000";

  26. /**

  27. * make a new dir in the hdfs

  28. *

  29. * @param dir the dir may like '/tmp/testdir'

  30. * @return boolean true-success, false-failed

  31. * @exception IOException something wrong happends when operating files

  32. */

  33. public static boolean mkdir(String dir) throws IOException {

  34. if (StringUtils.isBlank(dir)) {

  35. return false;

  36. }

  37. dir = uri + dir;

  38. Configuration conf = new Configuration();

  39. FileSystem fs = FileSystem.get(URI.create(dir), conf);

  40. if (!fs.exists(new Path(dir))) {

  41. fs.mkdirs(new Path(dir));

  42. }

  43. fs.close();

  44. return true;

  45. }

  46. /**

  47. * delete a dir in the hdfs.

  48. * if dir not exists, it will throw FileNotFoundException

  49. *

  50. * @param dir the dir may like '/tmp/testdir'

  51. * @return boolean true-success, false-failed

  52. * @exception IOException something wrong happends when operating files

  53. *

  54. */

  55. public static boolean deleteDir(String dir) throws IOException {

  56. if (StringUtils.isBlank(dir)) {

  57. return false;

  58. }

  59. dir = uri + dir;

  60. Configuration conf = new Configuration();

  61. FileSystem fs = FileSystem.get(URI.create(dir), conf);

  62. fs.delete(new Path(dir), true);

  63. fs.close();

  64. return true;

  65. }

  66. /**

  67. * list files/directories/links names under a directory, not include embed

  68. * objects

  69. *

  70. * @param dir a folder path may like '/tmp/testdir'

  71. * @return List<String> list of file names

  72. * @throws IOException file io exception

  73. */

  74. public static List<String> listAll(String dir) throws IOException {

  75. if (StringUtils.isBlank(dir)) {

  76. return new ArrayList<String>();

  77. }

  78. dir = uri + dir;

  79. Configuration conf = new Configuration();

  80. FileSystem fs = FileSystem.get(URI.create(dir), conf);

  81. FileStatus[] stats = fs.listStatus(new Path(dir));

  82. List<String> names = new ArrayList<String>();

  83. for (int i = 0; i < stats.length; ++i) {

  84. if (stats[i].isFile()) {

  85. // regular file

  86. names.add(stats[i].getPath().toString());

  87. } else if (stats[i].isDirectory()) {

  88. // dir

  89. names.add(stats[i].getPath().toString());

  90. } else if (stats[i].isSymlink()) {

  91. // is s symlink in linux

  92. names.add(stats[i].getPath().toString());

  93. }

  94. }

  95. fs.close();

  96. return names;

  97. }

  98. /*

  99. * upload the local file to the hds,

  100. * notice that the path is full like /tmp/test.txt

  101. * if local file not exists, it will throw a FileNotFoundException

  102. *

  103. * @param localFile local file path, may like F:/test.txt or /usr/local/test.txt

  104. *

  105. * @param hdfsFile hdfs file path, may like /tmp/dir

  106. * @return boolean true-success, false-failed

  107. *

  108. * @throws IOException file io exception

  109. */

  110. public static boolean uploadLocalFile2HDFS(String localFile, String hdfsFile) throws IOException {

  111. if (StringUtils.isBlank(localFile) || StringUtils.isBlank(hdfsFile)) {

  112. return false;

  113. }

  114. hdfsFile = uri + hdfsFile;

  115. Configuration config = new Configuration();

  116. FileSystem hdfs = FileSystem.get(URI.create(uri), config);

  117. Path src = new Path(localFile);

  118. Path dst = new Path(hdfsFile);

  119. hdfs.copyFromLocalFile(src, dst);

  120. hdfs.close();

  121. return true;

  122. }

  123. /*

  124. * create a new file in the hdfs.

  125. *

  126. * notice that the toCreateFilePath is the full path

  127. *

  128. * and write the content to the hdfs file.

  129. */

  130. /**

  131. * create a new file in the hdfs.

  132. * if dir not exists, it will create one

  133. *

  134. * @param newFile new file path, a full path name, may like '/tmp/test.txt'

  135. * @param content file content

  136. * @return boolean true-success, false-failed

  137. * @throws IOException file io exception

  138. */

  139. public static boolean createNewHDFSFile(String newFile, String content) throws IOException {

  140. if (StringUtils.isBlank(newFile) || null == content) {

  141. return false;

  142. }

  143. newFile = uri + newFile;

  144. Configuration config = new Configuration();

  145. FileSystem hdfs = FileSystem.get(URI.create(newFile), config);

  146. FSDataOutputStream os = hdfs.create(new Path(newFile));

  147. os.write(content.getBytes("UTF-8"));

  148. os.close();

  149. hdfs.close();

  150. return true;

  151. }

  152. /**

  153. * delete the hdfs file

  154. *

  155. * @param hdfsFile a full path name, may like '/tmp/test.txt'

  156. * @return boolean true-success, false-failed

  157. * @throws IOException file io exception

  158. */

  159. public static boolean deleteHDFSFile(String hdfsFile) throws IOException {

  160. if (StringUtils.isBlank(hdfsFile)) {

  161. return false;

  162. }

  163. hdfsFile = uri + hdfsFile;

  164. Configuration config = new Configuration();

  165. FileSystem hdfs = FileSystem.get(URI.create(hdfsFile), config);

  166. Path path = new Path(hdfsFile);

  167. boolean isDeleted = hdfs.delete(path, true);

  168. hdfs.close();

  169. return isDeleted;

  170. }

  171. /**

  172. * read the hdfs file content

  173. *

  174. * @param hdfsFile a full path name, may like '/tmp/test.txt'

  175. * @return byte[] file content

  176. * @throws IOException file io exception

  177. */

  178. public static byte[] readHDFSFile(String hdfsFile) throws Exception {

  179. if (StringUtils.isBlank(hdfsFile)) {

  180. return null;

  181. }

  182. hdfsFile = uri + hdfsFile;

  183. Configuration conf = new Configuration();

  184. FileSystem fs = FileSystem.get(URI.create(hdfsFile), conf);

  185. // check if the file exists

  186. Path path = new Path(hdfsFile);

  187. if (fs.exists(path)) {

  188. FSDataInputStream is = fs.open(path);

  189. // get the file info to create the buffer

  190. FileStatus stat = fs.getFileStatus(path);

  191. // create the buffer

  192. byte[] buffer = new byte[Integer.parseInt(String.valueOf(stat.getLen()))];

  193. is.readFully(0, buffer);

  194. is.close();

  195. fs.close();

  196. return buffer;

  197. } else {

  198. throw new Exception("the file is not found .");

  199. }

  200. }

  201. /**

  202. * append something to file dst

  203. *

  204. * @param hdfsFile a full path name, may like '/tmp/test.txt'

  205. * @param content string

  206. * @return boolean true-success, false-failed

  207. * @throws Exception something wrong

  208. */

  209. public static boolean append(String hdfsFile, String content) throws Exception {

  210. if (StringUtils.isBlank(hdfsFile)) {

  211. return false;

  212. }

  213. if(StringUtils.isEmpty(content)){

  214. return true;

  215. }

  216. hdfsFile = uri + hdfsFile;

  217. Configuration conf = new Configuration();

  218. // solve the problem when appending at single datanode hadoop env

  219. conf.set("dfs.client.block.write.replace-datanode-on-failure.policy", "NEVER");

  220. conf.set("dfs.client.block.write.replace-datanode-on-failure.enable", "true");

  221. FileSystem fs = FileSystem.get(URI.create(hdfsFile), conf);

  222. // check if the file exists

  223. Path path = new Path(hdfsFile);

  224. if (fs.exists(path)) {

  225. try {

  226. InputStream in = new ByteArrayInputStream(content.getBytes());

  227. OutputStream out = fs.append(new Path(hdfsFile));

  228. IOUtils.copyBytes(in, out, 4096, true);

  229. out.close();

  230. in.close();

  231. fs.close();

  232. } catch (Exception ex) {

  233. fs.close();

  234. throw ex;

  235. }

  236. } else {

  237. HdfsUtils.createNewHDFSFile(hdfsFile, content);

  238. }

  239. return true;

  240. }

  241. }

HdfsUtilsTest .java

  1. package test.com.xy6.demo.utils;

  2. import static org.junit.Assert.assertEquals;

  3. import java.util.ArrayList;

  4. import java.util.List;

  5. import org.junit.Test;

  6. import com.xy6.demo.utils.HdfsUtils;

  7. public class HdfsUtilsTest {

  8. public static String uri = "hdfs://192.168.1.118:9000";

  9. public String dir = "/user/output1";

  10. public String parentDir = "/user";

  11. @Test

  12. public void testMkdirNull1() {

  13. try{

  14. assertEquals(false, HdfsUtils.mkdir(null));

  15. assertEquals(false, HdfsUtils.mkdir(" "));

  16. assertEquals(false, HdfsUtils.mkdir(""));

  17. } catch(Exception ex){

  18. assertEquals(true, false);

  19. }

  20. }

  21. @Test

  22. public void testMkdirNormal1() {

  23. try{

  24. HdfsUtils.deleteDir(dir);

  25. boolean result = HdfsUtils.mkdir(dir);

  26. assertEquals(true, result);

  27. List<String> listFile = HdfsUtils.listAll(parentDir);

  28. boolean existFile = false;

  29. for(String elem : listFile){

  30. if(elem.equals(uri + dir)){

  31. existFile = true;

  32. break;

  33. }

  34. }

  35. assertEquals(true, existFile);

  36. } catch(Exception ex){

  37. ex.printStackTrace();

  38. assertEquals(true, false);

  39. }

  40. }

  41. @Test

  42. public void testDeleteDirNull1() {

  43. try{

  44. assertEquals(false, HdfsUtils.deleteDir(null));

  45. assertEquals(false, HdfsUtils.deleteDir(""));

  46. assertEquals(false, HdfsUtils.deleteDir(" "));

  47. } catch(Exception ex){

  48. assertEquals(true, false);

  49. }

  50. }

  51. @Test

  52. public void testDeleteDir() {

  53. try{

  54. assertEquals(true, HdfsUtils.mkdir(dir));

  55. assertEquals(true, HdfsUtils.deleteDir(dir));

  56. List<String> listFile = HdfsUtils.listAll(parentDir);

  57. boolean existFile = false;

  58. for(String elem : listFile){

  59. if(uri + dir == elem){

  60. existFile = true;

  61. break;

  62. }

  63. }

  64. assertEquals(false, existFile);

  65. } catch(Exception ex){

  66. ex.printStackTrace();

  67. assertEquals(true, false);

  68. }

  69. }

  70. @Test

  71. public void testListAllNull1() {

  72. try{

  73. List<String> listFile = new ArrayList<String>();

  74. assertEquals(listFile.toString(), HdfsUtils.listAll(null).toString());

  75. assertEquals(listFile.toString(), HdfsUtils.listAll(" ").toString());

  76. assertEquals(listFile.toString(), HdfsUtils.listAll("").toString());

  77. } catch(Exception ex){

  78. assertEquals(true, false);

  79. }

  80. }

  81. @Test

  82. public void testListAllEmptyFolder() {

  83. try{

  84. HdfsUtils.deleteDir(dir);

  85. assertEquals(true, HdfsUtils.mkdir(dir));

  86. List<String> listFile = HdfsUtils.listAll(dir);

  87. assertEquals(0, listFile.size());

  88. } catch(Exception ex){

  89. ex.printStackTrace();

  90. assertEquals(true, false);

  91. }

  92. }

  93. @Test

  94. public void testListAllNotExistFolder() {

  95. try{

  96. HdfsUtils.deleteDir(dir);

  97. List<String> listFile = HdfsUtils.listAll(dir);

  98. assertEquals(0, listFile.size());

  99. } catch(Exception ex){

  100. assertEquals(true, true);

  101. }

  102. }

  103. @Test

  104. public void testUploadLocalFile2HDFSNull1() {

  105. try{

  106. assertEquals(false, HdfsUtils.uploadLocalFile2HDFS(null, null));

  107. assertEquals(false, HdfsUtils.uploadLocalFile2HDFS("", ""));

  108. assertEquals(false, HdfsUtils.uploadLocalFile2HDFS(" ", " "));

  109. } catch(Exception ex){

  110. assertEquals(true, false);

  111. }

  112. }

  113. @Test

  114. public void testUploadLocalFile2HDFS() {

  115. String localFile = "F:/Program Files/eclipse/eclipse.ini";

  116. String remoteFile = dir + "/eclipse.ini";

  117. try{

  118. HdfsUtils.mkdir(dir);

  119. HdfsUtils.deleteHDFSFile(remoteFile);

  120. assertEquals(true, HdfsUtils.uploadLocalFile2HDFS(localFile, remoteFile));

  121. } catch(Exception ex){

  122. ex.printStackTrace();

  123. assertEquals(true, false);

  124. }

  125. }

  126. @Test

  127. public void testUploadLocalFile2HDFSLocalNotExist() {

  128. String localFile = "F:/Program Files/eclipse/eclipse2.ini";

  129. String remoteFile = dir + "/eclipse.ini";

  130. try{

  131. assertEquals(true, HdfsUtils.mkdir(dir));

  132. HdfsUtils.deleteHDFSFile(remoteFile);

  133. HdfsUtils.uploadLocalFile2HDFS(localFile, remoteFile);

  134. } catch(Exception ex){

  135. assertEquals(true, true);

  136. }

  137. }

  138. @Test

  139. public void testCreateNewHDFSFileNull1() {

  140. try{

  141. assertEquals(false, HdfsUtils.createNewHDFSFile(null, null));

  142. assertEquals(false, HdfsUtils.createNewHDFSFile(" ", " "));

  143. assertEquals(false, HdfsUtils.createNewHDFSFile("", ""));

  144. } catch(Exception ex){

  145. assertEquals(true, false);

  146. }

  147. }

  148. @Test

  149. public void testCreateNewHDFSFileNormal1() {

  150. try{

  151. String newFile = dir + "/file1.txt";

  152. String content = "hello file1";

  153. HdfsUtils.deleteHDFSFile(newFile);

  154. assertEquals(true, HdfsUtils.createNewHDFSFile(newFile, content));

  155. String result = new String(HdfsUtils.readHDFSFile(newFile));

  156. assertEquals(content, result);

  157. } catch(Exception ex){

  158. ex.printStackTrace();

  159. assertEquals(true, false);

  160. }

  161. }

  162. @Test

  163. public void testCreateNewHDFSFileFoldNotexist1() {

  164. try{

  165. String newFile = dir + "/file1.txt";

  166. String content = "hello file1";

  167. assertEquals(true, HdfsUtils.deleteDir(dir));

  168. assertEquals(true, HdfsUtils.createNewHDFSFile(newFile, content));

  169. } catch(Exception ex){

  170. ex.printStackTrace();

  171. assertEquals(true, false);

  172. }

  173. }

  174. @Test

  175. public void testDeleteHDFSFileNull1() {

  176. try{

  177. assertEquals(false, HdfsUtils.deleteHDFSFile(null));

  178. assertEquals(false, HdfsUtils.deleteHDFSFile(" "));

  179. assertEquals(false, HdfsUtils.deleteHDFSFile(""));

  180. } catch(Exception ex){

  181. assertEquals(true, false);

  182. }

  183. }

  184. @Test

  185. public void testDeleteHDFSFile() {

  186. this.testUploadLocalFile2HDFS();

  187. try{

  188. String remoteFile = dir + "/eclipse.ini";

  189. assertEquals(true, HdfsUtils.deleteHDFSFile(remoteFile));

  190. } catch(Exception ex){

  191. assertEquals(true, false);

  192. }

  193. }

  194. @Test

  195. public void testDeleteHDFSFileNotexist1() {

  196. try{

  197. String remoteFile = dir + "/eclipse2.ini";

  198. assertEquals(false, HdfsUtils.deleteHDFSFile(remoteFile));

  199. } catch(Exception ex){

  200. assertEquals(true, false);

  201. }

  202. }

  203. @Test

  204. public void testReadHDFSFileNull1() {

  205. try{

  206. assertEquals(null, HdfsUtils.readHDFSFile(null));

  207. assertEquals(null, HdfsUtils.readHDFSFile(" "));

  208. assertEquals(null, HdfsUtils.readHDFSFile(""));

  209. } catch(Exception ex){

  210. assertEquals(true, false);

  211. }

  212. }

  213. @Test

  214. public void testReadHDFSFile() {

  215. this.testUploadLocalFile2HDFS();

  216. try{

  217. String remoteFile = dir + "/eclipse.ini";

  218. String result = new String(HdfsUtils.readHDFSFile(remoteFile));

  219. assertEquals(true, result.length() > 0);

  220. } catch(Exception ex){

  221. ex.printStackTrace();

  222. assertEquals(true, false);

  223. }

  224. }

  225. @Test

  226. public void testAppendNull1() {

  227. try{

  228. assertEquals(false, HdfsUtils.append(null, null));

  229. assertEquals(false, HdfsUtils.append(" ", " "));

  230. assertEquals(false, HdfsUtils.append("", ""));

  231. } catch(Exception ex){

  232. assertEquals(true, false);

  233. }

  234. }

  235. @Test

  236. public void testAppend() {

  237. try{

  238. String newFile = dir + "/file1.txt";

  239. String content1 = "hello append1\r\n";

  240. String content2 = "hello append2\r\n";

  241. HdfsUtils.deleteHDFSFile(newFile);

  242. assertEquals(true, HdfsUtils.createNewHDFSFile(newFile, ""));

  243. assertEquals(true, HdfsUtils.append(newFile, content1));

  244. assertEquals(content1, new String(HdfsUtils.readHDFSFile(newFile)));

  245. assertEquals(true, HdfsUtils.append(newFile, content2));

  246. assertEquals(content1 + content2, new String(HdfsUtils.readHDFSFile(newFile)));

  247. } catch(Exception ex){

  248. ex.printStackTrace();

  249. assertEquals(true, false);

  250. }

  251. }

  252. }

java操作hdfs文件、文件夹相关推荐

  1. hadoop java操作hdfs

    hfds 是一种文件系统,用于存储hadoop将要处理的数据.适用于大规模分布式数据处理,是一个可扩展行的文件分布式系统: 优点 1.如果出现节点宕机,hdfs,可以持续监视,错误检查,容错处理,文档 ...

  2. Java 操作 HDFS

    HDFS 作为开源界比较成熟的分布式文件存储系统,适用于海量文件存储,本文介绍了如何使用 Java 操作 HDFS,采用 Maven 管理包. pom.xml <dependency>&l ...

  3. Java操作HDFS文件

    1.读取单个文件 [java] view plain copy Date date = DateUtil.getSpecifiedDayBefore(); String yesterday = Dat ...

  4. Java操作word模板文件

    关于导出word文档,之前想过用ireport但模板文件比较复杂不容易画.所以采取了Java操作word文件,替换word中的元素方法 模板文件如下 单位名称:$ACCTNAME$ NO: $SN$ ...

  5. Java操作HDFS文件系统

    对于操作HDFS文件系统,需要有一个入口,对于Hadoop来说,编程入口就是FileSystem. 例如我们要使用API创建一个文件夹: /*** @author vincent* @time 201 ...

  6. Java读取Hdfs的文件数据出现乱码的解决方案和办法

    使用JAVA api读取HDFS文件乱码踩坑 想写一个读取HFDS上的部分文件数据做预览的接口,根据网上的博客实现后,发现有时读取信息会出现乱码,例如读取一个csv时,字符串之间被逗号分割 英文字符串 ...

  7. Java操作FastDFS实现文件上传和下载

    前言:在GItHub上(地址:https://github.com/happyfish100),作者提供了fastdfs-client-java源码,源码里面提供了操作FastDFS的工具类,所以我们 ...

  8. Chimm.Excel —— 使用Java 操作 excel 模板文件生成 excel 文档

    内容已不在此处更新,请移步https://blog.csdn.net/chimmhuang/article/details/111251115 1. 项目介绍 Chimm.Excel 是什么? 该程序 ...

  9. java操作LINUX上文件,设置权限问题

    可以使用chmod u+x fileName;这样的话,可以使用Runtime类的方法执行一下命令行.进行权限赋值. ===================== File file = new Fil ...

最新文章

  1. 小程序:位置信息(Location)及微信小程序LBS解决方案实践
  2. go 二进制程序守护_GO-环境设置
  3. confluence未授权模板注入/代码执行 cve-2019-3396
  4. 抛开约束,增强模型:一行代码提升 ALBERT 表现
  5. 1.1 一个简单的脚本
  6. Windiws环境安装轻量级文件服务器ftpserver
  7. android gps 案例_GPS学习要点10
  8. 案例:需求问题的解决方案
  9. SSCLI中GC源码分析(1) - EE与BCL之间的调用接口FCall
  10. Linux内核调试 - 一般人儿我都不告诉他(一)
  11. linux格式化硬盘fat32,linux格式化硬盘教程 linux格式化硬盘教程是什么
  12. linux 安装pkg文件,Linux的pkg-config命令
  13. unity3d Hair real time rendering 真实头发实时渲染
  14. 简洁的HTML5和CSS3免费企业网站模板源码下载
  15. 【百度大脑新品体验】人脸面部动作识别
  16. GPS涉及到的各种时间转换(年月日,年积日,儒略日,GPS周及周内日或周内秒,星期几)python
  17. 2016年总结和2017年计划
  18. 物联网毕设分享 STM32 wifi照明控制系统 - 智能路灯(毕设分享)
  19. MATLAB仿真短路计算,基于MATLAB短路电流计算与仿真.doc
  20. 如何在基于python的聊天室中实现表情接收功能

热门文章

  1. java面试题(转载其他人,方便日常看)
  2. java会员卡的绑定和解绑_SpringMVC源码之参数解析绑定原理
  3. java对角线之和_java编程之计算矩阵对角线和(从命令窗输入数据)
  4. 一个详细的JTable使用例子
  5. Android入门第十五篇之ActivityGroup + GridView 实现Tab分页标签
  6. .net一个函数要用另一个函数的值_MATLAB中的神经网络工具箱(2)函数命令及模型搭建...
  7. linux 6中启动模式,linux6.x启动流程
  8. mac的python在哪里_python位置在mac osx
  9. a5松下驱动器参数设置表_松下伺服几个参数需要熟悉并掌握设置方法
  10. python3和2的区别大吗_python3和2为什么区别大吗