Writer:
Squence.Writer对象的获取方法有很多种重载方法:
对于:这个方法的使用。
参数分别为: FileSystem Configuration 文件的输出路径 key 和value类型的.class文件。此处键值对的处处类型不强制使用Writable类,只要能被Serializable序列化和反序列化即可。
获取Writer对象和配置好参数之后,就可以根据自己的书籍需求向目标文件中写入数据了(Writer.append(key,vlue))
package day20190726;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparator;
public class Test01 extends WritableComparator {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
Configuration conf=new Configuration();
URI uri=new URI("hdfs://hadoop104:8020");
FileSystem fs=FileSystem.get(uri, conf, "root");
Path path=new Path("/a.txt");
SequenceFile.Writer writer=null;
IntWritable key=new IntWritable();
Text value=new Text();
try {
System.out.println("进来了!");
writer=SequenceFile.createWriter(fs, conf, path, key.getClass(), value.getClass());
for(int i=0;i<10;i++) {
key.set(i);
value.set("haha");
writer.append(key, value);
}
}finally {
IOUtils.closeStream(writer);
}
IOUtils.closeStream(fs);
}
}
程序运行完毕之后,就可以在集群中查看文件了,但是文件不能用cat进行查看 ,而是使用hadoop dfs -text 文件名 |head方法进行查看。也可以容Squence.Reader对象对数据进行读取。
Reader
Reader实例的获取:
对于文件中数据的读取,需要先对文件数据的键值对的类型进行获取,
通过Reader.next(key,value)进行数据的读取和判断是否读取到文件的末尾
package day20190726;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.util.ReflectionUtils;
//SequnceFile的读操作
public class Test02 {
//SquenceFile.Reader实例反复调用next(方法)迭代读取记录
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
Configuration conf=new Configuration();
URI uri=new URI("hdfs://hadoop104:8020");
FileSystem fs =FileSystem.get(uri, conf, "root");
SequenceFile.Reader reader=null;
try {
reader=new SequenceFile.Reader(fs,new Path("/a.txt"),conf);
IntWritable key=(IntWritable) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
Text value=(Text)ReflectionUtils.newInstance(reader.getValueClass(), conf);
long position=reader.getPosition();
//获取数据并判断是否到文件的末尾
while(reader.next(key, value)) {
String syncSeen=reader.syncSeen()?"*":":";
//将获取的数据输出到控制台
System.out.println(position+"\t"+syncSeen+"\t"+key+"\t"+value);
position=reader.getPosition();
}
}finally {
IOUtils.closeStream(reader);
}
}
}
控制台输出结果: