向HDFS输出文件

本文介绍了如何向HDFS(Hadoop Distributed File System)输出文件。通过设置基础URL和目标路径,利用FileSystem类的get方法获取文件系统实例,然后进行文件操作。在使用OutputStream时需要注意,如果文件不存在,需要先关闭打开的文件流,再进行append操作,以避免错误。
摘要由CSDN通过智能技术生成

private static final String BASE_URL = "hdfs://10.15.0.208:8020";

String writePath = "/tmp/test.txt";

String finalUrl = BASE_URL+writePath;

FileSystem  fs = FileSystem.get(URI.create(finalUrl),conf);

        //要追加的文件流,inpath为文件  
        //InputStream in = new BufferedInputStream(new FileInputStream(finalUrl));
        fs.isDirectory(new Path(finalUrl));
        fs.isFile(new Path(finalUrl));
        if( !fs.isDirectory(new Path(finalUrl))&&!fs.isFile(new Path(finalUrl)))
        {
        System.out.println(finalUrl+"不存在于文件系统中");
        }else
        {
        System.out.println(finalUrl+"已存在");
        }
       
        OutputStream out = fs.append(new Path(finalUrl));  
        
        out.write("testWrite".getBytes());
        out.write("test".getBytes());
        out.write("Write".getBytes());
        //IOUtils.copyBytes(in, out, 4096, true);  
OutputStream pw = fs.create(new Path(finalUrl),false);
pw.write("hello testaaaaaaaaaaaaa".getBytes());
pw.write("bbbsss".getBytes());



System.out.println("写入成功");
pw.flush();

pw.close();


//如果文件不存在,create文件后要先把打开的文件流关闭,在进行append操作,否则会出错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值