Hadoop读写HDFS的Java Demo

package com.test;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;


public class HelloHadoopDemo {

    public static String fileName;

    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
        createHDFS();
        readHDFS();
        return;
    }

    private static void createHDFS() throws URISyntaxException, IOException, InterruptedException {
        Configuration configuration = new Configuration();
//        configuration.set("fs.hdfs.impl","org.apache.hadoop.hdfs.DistributedFileSystem");
        String path = "hdfs://127.0.0.1:9000/first/hello/";
        URI uri = new URI(path);
        FileSystem fileSystem = FileSystem.get(uri, configuration, "root");//user不是root,没有权限写
        fileName =  "file" + new Date().getTime();
        FSDataOutputStream fsDataOutputStream = fileSystem.create(new Path(path + fileName), false);
        String json = "hello hadoop";
        fsDataOutputStream.write(json.getBytes());
        fsDataOutputStream.close();
        System.out.println(fileName);
//        Thread.sleep(3000L);
    }

    private static void readHDFS() throws URISyntaxException, IOException, InterruptedException {
        String path = "hdfs://127.0.0.1:9000/first/hello/";
        URI uri = new URI(path);
        FileSystem fileSystem = FileSystem.get(uri, new Configuration());//user不是root,没有权限写
        FSDataInputStream fsDataInputStream = fileSystem.open(new Path(path + fileName));
        byte[] bytes = new byte[1024];
        int length = -1;
        while((length=fsDataInputStream.read(bytes)) != -1){
            String s = new String(bytes, 0, length);
            System.out.println(s);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值