hdfs例子之读写MapFile

2 篇文章 0 订阅
package mytest;

import java.io.IOException;
import java.net.URI;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.Text;

public class MyMapFileTest {

	private static void write() throws IOException {
		Configuration conf = new Configuration();
		URI uri = URI.create("file:///home/yunpeng/mapFile.map");
		FileSystem fs = FileSystem.get(uri, conf);
		MapFile.Writer writer = null;
		writer = new MapFile.Writer(conf, fs, uri.getPath(), Text.class, Text.class);

		//通过writer向文档中写入记录  
		writer.append(new Text("key"), new Text("value"));
		IOUtils.closeStream(writer);//关闭write流  
	}

	private static void read() throws IOException {
		Configuration conf = new Configuration();
		URI uri = URI.create("file:///home/yunpeng/mapFile.map");
		FileSystem fs = FileSystem.get(uri, conf);
		MapFile.Reader reader = null;
		reader = new MapFile.Reader(fs, uri.getPath(), conf);

		//通过writer向文档中写入记录  
		Text key = new Text();
		Text value = new Text();
		while (reader.next(key, value)) {
			System.out.println(key);
			System.out.println(value);
		}
		IOUtils.closeStream(reader);//关闭write流  
	}

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

 

写对象:

	Configuration conf = new Configuration();
		URI uri = URI.create("file:///home/yunpeng/mapFile.map");
		FileSystem fs = FileSystem.get(uri, conf);
		MapFile.Writer writer = new MapFile.Writer(conf, fs, uri.getPath(), Text.class, BytesWritable.class);

		//write dataRepository
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		ObjectOutputStream objOutput = new ObjectOutputStream(output);
		objOutput.writeObject(dataRepository);
		byte[] data = output.toByteArray();
		///通过writer向文档中写入记录  
		writer.append(new Text("data"), new BytesWritable(data));
		//关闭write流
		IOUtils.closeStream(writer);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值