hadoop之HDFS对文件的相关操作

 hadoop对文件的操作:
  工具类中的代码:
 /**
 * 
 * @author:戴桥冰 2015-10-4 下午7:48:55 content:HDFS文件的操作
 */
    public class Utils{

    private static Configuration conf=new Configuration();

    public static FileSystem getFileSystem() throws Exception{
        FileSystem fs=FileSystem.get(conf);
        return fs;
    }
}
  1 创建文件夹:fileSystem.mkdirs(path),其中path为Path类型,其中fileSystem为FileSystem类型,核心代码如    

    /**
 * 创建文件夹
 * 
 * @throws Exception
 * @throws IOException
 */
public void createDirectory() throws IOException, Exception {
path = new Path("/opt/data/hadoop/test");
boolean isSuccess = Utils.getFileSystem().mkdirs(path);// 创建文件夹
System.out.println(isSuccess ? "文件夹创建成功" : "文件夹创建失败");  
}
 2 创建文件并且写入文件:fileSystem.create(path),其中path为Path类型,dataOutputStream.writeUTF( str);// 写入str的字符串到文件中
    /**
     * 创建文件 
     * @throws Exception
     */
    public void createFile() throws Exception {
        path = new Path("/opt/data/hadoop/test.txt");
        FileSystem fs = Utils.getFileSystem();
        FSDataOutputStream dataOutputStream = fs.create(path);// 创建文件
        dataOutputStream
                .writeUTF("this is the hadoop programming,not is the hello word!");// 写入字符串到文件中
    }// 创建文件成功,并且成功的写入
   3 删除文件,文件夹以及其中的内容:fs.deleteOnExit(path);
   代码如下:
    /**
     * 删除文件,文件夹以及其中的内容
     * @throws Exception 
     */
    public void deleteFile() throws Exception{
        FileSystem fs=Utils.getFileSystem();
        path=new Path("/opt/data/hadoop/test");
        fs.deleteOnExit(path);
    }//文件删除成功

4 查看文件列表:FileStatus[] fileStatus = fs.listStatus(path);
代码如下:

/**
     * 查看文件列表
     * 
     * @throws Exception
     */ 
    public void lookFileList() throws Exception {
        FileSystem fs = Utils.getFileSystem();
        Path path = new Path("/opt/data/hadoop");
        FileStatus[] fileStatus = fs.listStatus(path);
        for (FileStatus file : fileStatus) {
            Path p = file.getPath();
            String isDirectory = file.isDir() ? "文件夹:" : "文件:";
            System.out.println(isDirectory + " " + p);
        }
    }//获取文件列表成功
5 上传下载文件:fs.copyFromLocalFile(srcPath, path);
    /**
     * 上传,下载文件
     * @throws Exception 
     */
    public void upFile() throws Exception{
        FileSystem fs=Utils.getFileSystem();
        Path srcPath=new Path("E:/tmp/AppTest.java");//需要上传的文件
        Path path=new Path("/opt/data/hadoop/test");//需要上传到的目录
        fs.copyFromLocalFile(srcPath, path);
    }//上传文件成功
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值