SequenceFile 读写操作

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.CompressionType;
import org.apache.hadoop.io.SequenceFile.Reader;
import org.apache.hadoop.io.SequenceFile.Writer;
import org.apache.hadoop.io.Text;

public class TestSequenceFile {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// // TODO Auto-generated method stub
		 Configuration conf = new Configuration();
		 Path seqFile = new Path("/test/seqFile2.seq");
		 // Writer内部类用于文件的写操作,假设Key和Value都为Text类型
		 SequenceFile.Writer writer = SequenceFile.createWriter(conf,
		 Writer.file(seqFile), Writer.keyClass(Text.class),
		 Writer.valueClass(Text.class),
		 Writer.compression(CompressionType.NONE));

		 // 通过writer向文档中写入记录
		 writer.append(new Text("key"), new Text("value"));
		
		 IOUtils.closeStream(writer);// 关闭write流
		 // 通过reader从文档中读取记录
		 SequenceFile.Reader reader = new SequenceFile.Reader(conf,
		 Reader.file(seqFile));
		 Text key = new Text();
		 Text value = new Text();
		 while (reader.next(key, value)) {
		 System.out.println(key);
		 System.out.println(value);
		 }
		 IOUtils.closeStream(reader);// 关闭read流

		
	}

}



其中遇到一个问题,我重复执行写入操作,发现并没有按照我所想的append到现有文件上去。而是还是只有最新的append的数据。然后查看了一下源码,发现每次都执行了:

out = fs.create(p, true, bufferSize, replication, blockSize, progress);

第二个参数写死了为true(是否overwrite),即每次都会覆盖同名的文件,如果为false会抛文件已经存在的异常。

当时感觉非常奇怪,为啥这么处理的,后面想明白了这件事情,sequenceFile 为hdfs的一种文件类型,hdfs提倡一次写入多次读取,而不提倡你去追加改写一个现有的文件。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值