使用java API操作hdfs--拷贝部分文件到hdfs

要求如下:

       自行在本地文件系统生成一个大约一百多字节的文本文件,写一段程序(可以利用Java API或C API),读入这个文件,并将其第101-120字节的内容写入HDFS成为一个新文件。

 

Image(42)

Image(43)

 

 

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

public class ShengChen {

        public static void main(String[] args) throws IOException {

                // TODO Auto-generated method stub

                File file=new File("/home/weiguohui/shengchen.txt");

                if (!file.exists()) {

                        file.createNewFile();

                }

                byte[] bytes=new byte[130];

                for (int i = 0; i < bytes.length; i++) {

                        bytes[i]=(byte) i;

                }

                FileOutputStream fos=new FileOutputStream(file);

                fos.write(bytes);

        }

}

 

 

Image(44)

Image(45)

正好写入了20个字节

代码:

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.InputStream;

import org.apache.hadoop.io.IOUtils;

import java.io.BufferedInputStream;

import org.apache.hadoop.fs.FileSystem;

import org.apache.hadoop.conf.Configuration;

import java.net.URI;

import java.io.OutputStream;

import org.apache.hadoop.fs.Path;

public class CopyFileToHdfs {

        public static void main(String[] args)  {

                // TODO Auto-generated method stub

                File file=new File("/home/weiguohui/shengchen.txt");

                InputStream in=null;

                String dst=args[0];

                Configuration conf = new Configuration();

                byte[] bytes=new byte[1024];

                int offset=100;

                int len=20;

                int numberRead=0;

                OutputStream os=null;

                try {

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

                        in= new BufferedInputStream(new FileInputStream(file));

                        os=fs.create(new Path(dst));

                        while((numberRead=in.read(bytes))!=-1){

                                os.write(bytes, offset, len);

                        }

                        //IOUtils.copyBytes(in, os, 4096, false);

                } catch (Exception e) {

                        // TODO Auto-generated catch block

                        e.printStackTrace();

                }finally {

                        IOUtils.closeStream(in);

                        IOUtils.closeStream(os);

                }

        }

}

 

转载于:https://www.cnblogs.com/beigongfengchen/p/5472746.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值