通过FSDataOutputStream向HDFS上写数据

FSDataOutputStream,这个类重载了很多write方法,用于写入很多类型的数据:比如字节数组,long,int,char等等。

像FSDataInputStream一样,要获得FSDataOutputStream的实例,必须通过FileSystem该类来和HDFS建立连接,然后通过路径返回FSDataOutputStream实例。

FileSystem返回FSDataOutputStream实例的方法有两组

  1.create(Path p)函数,创建一个空文件,然后可以向该文件顺序写入

  2.append(Path p)函数,打开一个已有文件,并最做文件末尾追加数据

 

FileSystemUtil

public class FileSystemUtil {
    
    private static FileSystem fileSystem;
    
   //代码中Kerberos认证根据自己环境替换即可
public synchronized static FileSystem getFileSystem() throws IOException{ if(fileSystem==null){ Configuration conf=new Configuration(); conf.set("fs.defaultFS", "hdfs://host12.master.cluster.enn.cn:8020"); conf.set("dfs.client.block.write.replace-datanode-on-failure.policy" ,"NEVER" ); conf.set("dfs.client.block.write.replace-datanode-on-failure.enable" ,"true" ); KerberosClient.login(Constants.Kerberos_USER_NAME, Constants.Kerberos_KEYTAB_FILE); fileSystem=FileSystem.get(conf); } return fileSystem; } public synchronized static void shutdown(){ if(fileSystem!=null){ try { fileSystem.close(); fileSystem=null; } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) throws Exception { System.out.println(FileSystemUtil.getFileSystem()); } }

 

FSDataOutputStreamTest

public class FSDataOutputStreamTest{
    private static final Logger LOGGER = LoggerFactory.getLogger(Test.class);
    private static void hfdsAppendData() {
        String filePath = "/user/hive/warehouse/test.db/t_test/day=2017-11-29/hour=16/backup_ycgqh";
        FileSystem fileSystem = null;
        FSDataOutputStream fileOutputStream = null;
        Path hdfsPath = new Path(filePath);
        try {
            fileSystem=FileSystemUtil.getFileSystem();
            if (!fileSystem.exists(hdfsPath)) {
                fileOutputStream = fileSystem.create(hdfsPath,false);
            }else{
                fileOutputStream = fileSystem.append(hdfsPath);
            }
            fileOutputStream.writeUTF("");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                FileSystemUtil.shutdown();
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/weishao-lsv/p/8159285.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值