hadoop之HDFS对文件的相关操作

来源:互联网 发布:linux 查看服务器类型 编辑:程序博客网 时间:2024/06/06 02:18
 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
原创粉丝点击