java 实现 hdfs写入,查询 ,创建,删除功能

 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.Properties;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.Progressable;
import org.junit.Test;
 
public class HdfsDemo {
 
    private static String SOURCE_PATH = "C:/Users/jackie/Desktop/log.txt";
    private static String DEST_PATH = "/home/data4.txt";
    private static String MASTER_URI = "hdfs://192.168.220.128:9000";
 
    public static void main(String[] args) throws Exception {
        Properties properties = System.getProperties();
        properties.setProperty("HADOOP_USER_NAME", "root");
        // TODO Auto-generated method stub
        //testUpload();
        //testDownload();
        //testMakeDir();
        //testDelete();
        //testCat();
        testLs();
    }
    /**
     * 测试上传文件
     * 如果下述代码抛出异常:
     * org.apache.hadoop.security.AccessControlException: Permission denied: user=xxx, access=WRITE.关闭防火墙
     * 则表明上传文件的用户没有权限。解决方式如下:
     * 1.配置环境变量HADOOP_USER_NAME, 并设置值为有访问hadoop集群有权限的用户,比如:hadoop。源码调试发现hadoop会首先从环境变量中去查找上传文件的用户名。查找不到会议pc的名字作为用户名。
     * 2.赋予hdfs上的文件夹/hbase/upload/读写权限。 命令是:hadoop fs -chmod 777  /hbase/upload。这样,可以保证上传文件到该目录成功,但上传到其他目录依然无权限。
     *
     * @throws Exception
     * @author lihong10 2017年12月9日 上午10:42:30
     */
     
    public static void testUpload() throws Exception {
 
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(new URI(MASTER_URI), conf);
        InputStream in = new FileInputStream(SOURCE_PATH);
        OutputStream out = fs.create(new Path(DEST_PATH), new Progressable() {
            @Override
            public void progress() {
                System.out.println("上传完一个设定缓存区大小容量的文件!");
            }
        });
        IOUtils.copyBytes(in, out, conf);
 
       /* byte[] buffer = new byte[1024];
        int len = 0;
        while((len=in.read(buffer))>0){
            out.write(buffer, 0, len);
        } 
        out.flush();
        in.close();
        out.close(); */
    }
 
 
    /**
     * 测试下载文件
     * @throws Exception
     */
     
    public static void testDownload() throws Exception {
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(new URI(MASTER_URI), conf);
//        InputStream in = new FileInputStream("e:\\hadoop.avi");
//        OutputStream out = fs.create(new Path("/demo/b.avi"));
        InputStream in = fs.open(new Path(DEST_PATH));
        OutputStream out = new FileOutputStream("d:\\test.txt");
        IOUtils.copyBytes(in, out, conf);
 
      /*byte[] buffer = new byte[1024];
        int len = 0;
        while((len=in.read(buffer))>0){
            out.write(buffer, 0, len);
        } 
        out.flush();
        in.close();
        out.close();*/
    }
 
    /**
     * 复制文件到远程文件系统,也可以看做是上传
     * @param conf
     * @param uri
     * @param local
     * @param remote
     * @throws IOException
     */
    public static void copyFile(Configuration conf, String uri, String local, String remote) throws IOException {
        FileSystem fs = FileSystem.get(URI.create(uri), conf);
        fs.copyFromLocalFile(new Path(local), new Path(remote));
        System.out.println("copy from: " + local + " to " + remote);
        fs.close();
    }
 
    @Test
    public void testCopyFile() throws IOException {
        // 使用命令:hadoop fs -ls  /hbase/upload, 可以查看复制到/hbase/upload目录下的文件
        copyFile(new Configuration(), MASTER_URI, SOURCE_PATH, "/hbase/upload/settings01.jar");
    }
 
    /**
     * 在hdfs文件系统下创建目录
     * @param conf
     * @param uri
     * @param remoteFile
     * @throws IOException
     */
    public static void makeDir(Configuration conf, String uri, String remoteFile) throws IOException {
        FileSystem fs = FileSystem.get(URI.create(uri), conf);
        Path path = new Path(remoteFile);
 
        fs.mkdirs(path);
        System.out.println("创建文件夹" + remoteFile);
    }
 
     
    public static void testMakeDir() throws IOException {
        //可以通过:hadoop fs -ls  /hbase/upload。   查看创建的目录subdir01
        makeDir(new Configuration(), MASTER_URI, "/hbase/upload/subdir01");
    }
 
 
    /**
     * 删除文件
     * @param conf
     * @param uri
     * @param filePath
     * @throws IOException
     */
    public static void delete(Configuration conf, String uri, String filePath) throws IOException {
        Path path = new Path(filePath);
        FileSystem fs = FileSystem.get(URI.create(uri), conf);
        fs.deleteOnExit(path);
        System.out.println("Delete: " + filePath);
        fs.close();
    }
 
   
    public static  void testDelete() throws IOException {
        delete(new Configuration(), MASTER_URI, "/home/data3");
    }
 
 
    /**
     * 查看文件内容
     * @param conf
     * @param uri
     * @param remoteFile
     * @throws IOException
     */
    public static void cat(Configuration conf, String uri, String remoteFile) throws IOException {
        Path path = new Path(remoteFile);
        FileSystem fs = FileSystem.get(URI.create(uri), conf);
        FSDataInputStream fsdis = null;
        System.out.println("cat: " + remoteFile);
        try {
            fsdis = fs.open(path);
            IOUtils.copyBytes(fsdis, System.out, 4096, false);
        } finally {
            IOUtils.closeStream(fsdis);
            fs.close();
        }
    }
 
    
    public static  void testCat() throws IOException {
        //hbase/hbase.version 这个文件已经存在
        cat(new Configuration(), MASTER_URI, "/home/data4.txt");
    }
 
    /**
     * 查看目录下面的文件
     * @param conf
     * @param uri
     * @param folder
     * @throws IOException
     */
    public static void ls(Configuration conf, String uri, String folder) throws IOException {
        Path path = new Path(folder);
        FileSystem fs = FileSystem.get(URI.create(uri), conf);
        FileStatus[] list = fs.listStatus(path);
        System.out.println("ls: " + folder);
        System.out.println("==========================================================");
        for (FileStatus f : list) {
            System.out.printf("name: %s, folder: %s, size: %d\n", f.getPath(), f.isDirectory(), f.getLen());
        }
        System.out.println("==========================================================");
        fs.close();
    }
 
   
    public  static void testLs() throws IOException {
        ls(new Configuration(), MASTER_URI, "/home");
    }
 
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Java API操作HDFS的示例代码,创建文件并写入内容: ```java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; public class HdfsDemo { public static void main(String[] args) throws IOException { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); // 创建文件并写入内容 String filePath = "/user/hadoop/test.txt"; Path file = new Path(filePath); if (fs.exists(file)) { System.out.println("文件已存在,删除文件"); fs.delete(file, true); } OutputStream os = fs.create(file); os.write("Hello, Hadoop!".getBytes("UTF-8")); os.flush(); os.close(); System.out.println("文件创建成功"); // 读取文件内容 InputStream is = fs.open(file); IOUtils.copyBytes(is, System.out, 4096, false); IOUtils.closeStream(is); fs.close(); } } ``` 在上述示例代码中,使用`FileSystem.get(conf)`方法获取到HDFS文件系统对象,然后使用`fs.exists(file)`方法判断文件是否已经存在,如果存在则使用`fs.delete(file, true)`方法删除文件。接着使用`fs.create(file)`方法创建文件,并使用`os.write()`方法写入内容。最后使用`fs.open(file)`方法读取文件内容,使用`IOUtils.copyBytes()`方法将内容输出到控制台。 需要注意的是,在操作HDFS时,需要配置`core-site.xml`和`hdfs-site.xml`两个配置文件。`core-site.xml`配置文件中需要配置Hadoop集群的名称和HDFS的访问地址,`hdfs-site.xml`配置文件中需要配置HDFS的副本数和数据块大小等信息。在本地运行Java程序时,需要将这两个配置文件放在classpath下,或者在程序中使用`conf.addResource()`方法加载配置文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值