• 本地Eclipse连接HDFS进行简单的文件操作


           昨天总结了一点自己在搭建Hadoop完全分布式环境过程中遇到的几个小问题以及解决方案,今天在搭建成功的环境中进行了简单的文件操作,包括:文件目录的创建、文件的创建、本地文件的上传、文件的重命名、文件的删除以及其他几个关于文件的操作,希望对初学的练习者有所帮助。

      1 package org.apache.hadoop.examples;
      2 
      3 
      4 import java.io.BufferedOutputStream;
      5 import java.io.IOException;
      6 import java.net.URI;
      7 import java.text.SimpleDateFormat;
      8 import java.util.Date;
      9 
     10 import org.apache.hadoop.conf.Configuration;
     11 import org.apache.hadoop.fs.BlockLocation;
     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.hadoop.hdfs.DistributedFileSystem;
     17 import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
     18 import org.junit.Before;
     19 import org.junit.Test;
     20 
     21 public class FileDemo {
     22     private  Configuration conf = new Configuration();//这里创建conf对象有一个默认参数,boolean loadDefaults,默认为true
     23     private String rootPath=new String("hdfs://192.168.56.10:9000/");
     24     private FileSystem coreSys=null;
     25     /**
     26      * 每次执行之前初始化操作,初始化FileSystem核心对象
     27      */
     28     @Before
     29     public void iniFileSystemObject(){
     30         try {
     31             coreSys=FileSystem.get(URI.create(rootPath), conf);
     32         } catch (IOException e) {
     33             System.out.println("初始化HDFS核心文件对象失败:"+e.getLocalizedMessage());
     34         }
     35     }
     36     /**
     37      * 在HDFS上创建文件目录
     38      */
     39     @Test
     40     public void createDirOnHDFS(){
     41            Path demoDir=new Path(rootPath+"demoDir");
     42            boolean isSuccess=true;
     43            try {
     44                isSuccess=coreSys.mkdirs(demoDir);
     45            } catch (IOException e) {
     46                isSuccess=false;
     47            }
     48            System.out.println(isSuccess?"目录创建成功!":"目录创建失败!");
     49            
     50     }
     51     /**
     52      * 在HDFS上创建文件
     53      * @throws Exception 
     54      */
     55     @Test
     56     public void createFile() throws Exception{
     57                 Path hdfsPath = new Path(rootPath + "user/hdfsupload/createDemoFile");
     58                 System.out.println(coreSys.getHomeDirectory());
     59                 String content = "Hello hadoop,this is first time that I create file on hdfs";
     60                 FSDataOutputStream fsout = coreSys.create(hdfsPath);
     61                 BufferedOutputStream bout = new BufferedOutputStream(fsout);
     62                 bout.write(content.getBytes(), 0, content.getBytes().length);
     63                 bout.close();
     64                 fsout.close();
     65                 System.out.println("文件创建完毕!");
     66     }
     67     /**
     68      * 从本地上传任意文件到服务器HDFS环境
     69      * @throws Exception
     70      */
     71     @Test
     72     public void uploadFile() throws Exception{
     73          Configuration conf = new Configuration();
     74          Path remotePath=new Path(rootPath+"user/");
     75          coreSys.copyFromLocalFile(new Path("D:\VirtualBox\Users"), remotePath);
     76          System.out.println("Upload to:"+conf.get("fs.default.name"));
     77          FileStatus [] files=coreSys.listStatus(remotePath);
     78          for(FileStatus file:files){
     79              System.out.println(file.getPath().toString());
     80          }
     81     }
     82     /**
     83      * 重命名文件名
     84      */
     85     @Test
     86     public void renameFile(){
     87         Path oldFileName=new Path(rootPath+"user/hdfsupload/createDemoFile");
     88         Path newFileName=new Path(rootPath+"user/hdfsupload/renameDemoFile");
     89         boolean isSuccess=true;
     90         try {
     91             isSuccess=coreSys.rename(oldFileName, newFileName);
     92         } catch (IOException e) {
     93              isSuccess=false;
     94         }
     95         System.out.println(isSuccess?"重命名成功!":"重命名失败!");
     96     }
     97     /**
     98      * 删除文件
     99      */
    100     @Test
    101     public void deleteFile(){
    102         Path deleteFile=new Path(rootPath+"user/hdfsupload/job.jar");
    103         boolean isSuccess=true;
    104         try {
    105             isSuccess=coreSys.delete(deleteFile, false);
    106         } catch (IOException e) {
    107             isSuccess=false;
    108         }
    109         System.out.println(isSuccess?"删除成功!":"删除失败!");
    110     }
    111     /**
    112      * 查找某个文件是否存在
    113      */
    114     @Test
    115     public void findFileIsExit(){
    116           Path checkFile=new Path(rootPath+"user/hdfsupload/job.jar");
    117           boolean isExit=true;
    118           try {
    119               isExit=coreSys.exists(checkFile);
    120             } catch (IOException e) {
    121                 isExit=false;
    122            }
    123         System.out.println(isExit?"文件存在!":"文件不存在!");
    124     }
    125     /**
    126      * 查看某个文件的最后修改时间
    127      * @throws IOException 
    128      */
    129     @Test
    130     public void watchFileLastModifyTime() throws IOException{
    131          Path targetFile=new Path(rootPath+"user/hdfsupload/renameDemoFile");
    132          FileStatus fileStatus=coreSys.getFileStatus(targetFile);
    133          Long lastTime=fileStatus.getModificationTime();
    134          Date date=new Date(lastTime);
    135          SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    136          System.err.println("文件的最后修改时间为:"+format.format(date));
    137     }
    138     /**
    139      * 获取某个路径下面的所有文件
    140      * @throws IOException 
    141      */
    142     @Test
    143     public void getUnderDirAllFile() throws IOException{
    144         Path targetDir=new Path(rootPath+"user/hdfsupload/");
    145         FileStatus []fileStatus=coreSys.listStatus(targetDir);
    146         for(FileStatus file:fileStatus){
    147             System.out.println(file.getPath()+"--"+file.getGroup()+"--"+file.getBlockSize()+"--"+file.getLen()+"--"+file.getModificationTime()+"--"+file.getOwner());
    148         }
    149     }
    150     /**
    151      * 查看某个文件在HDFS集群的位置
    152      * @throws IOException 
    153      */
    154     @Test
    155     public void findLocationOnHadoop() throws IOException{
    156         Path targetFile=new Path(rootPath+"user/hdfsupload/AA.txt");
    157         FileStatus fileStaus=coreSys.getFileStatus(targetFile);
    158         BlockLocation []bloLocations=coreSys.getFileBlockLocations(fileStaus, 0, fileStaus.getLen());
    159         for(int i=0;i<bloLocations.length;i++){
    160             System.out.println("block_"+i+"_location:"+bloLocations[i].getHosts()[0]);
    161         }
    162         
    163     }
    164     /**
    165      * 获取集群上结点的信息
    166      * @throws IOException 
    167      */
    168     @Test
    169     public void getNodeMsgHdfs() throws IOException{
    170          DistributedFileSystem distributedFileSystem=(DistributedFileSystem) coreSys;
    171          DatanodeInfo []dataInfos=distributedFileSystem.getDataNodeStats();
    172          for(int j=0;j<dataInfos.length;j++){
    173              System.out.println("DataNode_"+j+"_Name:"+dataInfos[j].getHostName()+"--->"+dataInfos[j].getDatanodeReport()+"-->"+
    174             dataInfos[j].getDfsUsedPercent()+"-->"+dataInfos[j].getLevel());
    175          }
    176     }
    177     
    178 }

     

  • 相关阅读:
    tomcat报错:java.io.IOException: 您的主机中的软件中止了一个已建立的连接。
    mysql 的 case when 用法
    分享几个能用的 editplus 注册码
    windows 时间同步至最新时间方法 | windows 时间同步服务器
    tomcat 如何登录 Server Status、Manager App、Host Manager
    Eclipse将java项目导出可执行的jar文件
    Java 中将字符串与 unicode 相互转换的工具类
    解决Lost connection to MySQL server during query错误方法
    gt,gte,lt,lte缩写的含义
    python 打印调用栈
  • 原文地址:https://www.cnblogs.com/ljhoracle/p/4966980.html
Copyright © 2020-2023  润新知