使用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