windows下eclipse操作hdfs上面的文件

我们使用eclipse编程连接hadoop完成在hdfs上面创建文件。
实验代码如下:

public class FileDemo {
    `private Configuration conf = new Configuration();`// 这里创建conf对象有一个默认参数,boolean
                                                        // loadDefaults,默认为true
    private String rootPath = new String("hdfs://192.168.13.129:9000/");
    private FileSystem coreSys = null;

    /**
     * 每次执行之前初始化操作,初始化FileSystem核心对象
     */
    public void iniFileSystemObject() {
        try {
            coreSys = FileSystem.get(URI.create(rootPath), conf);
        } catch (IOException e) {
            System.out.println("初始化HDFS核心文件对象失败:" + e.getLocalizedMessage());
        }
    }
    /**
     * 在HDFS上创建文件
     * 
     * @throws Exception
     */
    public void createFile() throws Exception {
        Path hdfsPath = new Path(rootPath + "/test/createfile");
        // System.out.println(coreSys.getHomeDirectory());
        // System.setProperty("hadoop.home.dir",
        // "D:/linux/hadoop-2.6.4/hadoop-2.6.4/bin");
        String content = "Hello hadoop,this is first time that I create file on hdfs";
        FSDataOutputStream fsout = coreSys.create(hdfsPath);
        BufferedOutputStream bout = new BufferedOutputStream(fsout);
        bout.write(content.getBytes(), 0, content.getBytes().length);
        bout.close();
        fsout.close();
        System.out.println("文件创建完毕!");
    }
    }

在eclipse上面新建一个map reduce工程。导入jar包。在hadoop中share下面的mapreduce下面的所有jar包都导入到工程中。
下载对应版本的
hadoop.dll,winutils.exe,winutils.pdb三个文件,hadoop.dll,winutils.exe文件放在windows下面hadoop中的bin目录下面,winutils.exe拷贝到c/windows/System32下面。
下面记得配置windows解压后hadoop中bin到环境变量中。完成上面的配置,我们开始讲解上面的代码

private Configuration conf = new Configuration();
private String rootPath = new String("hdfs://192.168.13.129:9000/");
    private FileSystem coreSys = null;

创建一个conf,rootPath里面主要设置hdfs的ip地址和端口,地址和端口见linux上面core-site.xml文件夹。
写一个FileSystem用来创建文件和建立文件输出流。

Path hdfsPath = new Path(rootPath + "/test/createfile");
FSDataOutputStream fsout = coreSys.create(hdfsPath);

path主要填写创建文件的位置。
测试代码如下:

public class HdfsTest {
    public static void main(String[] args) {
        FileDemo filedemo = new FileDemo();
        filedemo.iniFileSystemObject();
        try {
            filedemo.createFile();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

执行完测试代码,我们就可以在DFS Location重新连接后找到新建的文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值