我想要的是将hdfs上的一个包含xml数据的序列文件转换为hdfs上的.xml文件。
在Google上搜索并找到以下代码。我根据自己的需要进行了修改,以下是代码..
public class SeqFileWriterCls {
public static void main(String args[]) throws Exception {
System.out.println("Reading Sequence File");
Path path = new Path("seq_file_path/seq_file.seq");
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
SequenceFile.Writer writer = null;
SequenceFile.Reader reader = null;
FSDataOutputStream fwriter = null;
OutputStream fowriter = null;
try {
reader = new SequenceFile.Reader(fs, path, conf);
//writer = new SequenceFile.Writer(fs, conf,out_path,Text.class,Text.class);
Writable key = (Writable) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
Writable value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), conf);
while (reader.next(key, value)) {
//i am just editing the path in such a way that key will be my filename and data in it will be the value
Path out_path = new Path(""+key);
String string_path = out_path.toString();
String clear_path=string_path.substring(string_path.lastIndexOf("/")+1);
Path finalout_path = new Path("path"+clear_path);
System.out.println("the final path is "+finalout_path);
fwriter = fs.create(finalout_path);
fwriter.writeUTF(value.toString());
fwriter.close();
FSDataInputStream in = fs.open(finalout_path);
String s = in.readUTF();
System.out.println("file has: -" + s);
//fowriter = fs.create(finalout_path);
//fowriter.write(value.toString());
System.out.println(key + " <===> :" + value.toString());
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeStream(reader);
fs.close();
}
}
我正在使用&#34; FSDataOutputStream&#34;将数据写入HDFS并使用的方法是&#34; writeUTF&#34;问题是,当我写入hdfs文件时,一些额外的字符正在进入数据的开始。但是当我打印数据时,我看不到额外的字符。
我尝试使用writeChars()但是甚至不会工作。
有没有办法避免这个?或者有没有其他方法将数据写入HDFS ???
请帮忙......
答案 0 :(得分:1)
writeUTF(String str)
方法的JavaDoc表示以下内容:
使用修改后的UTF-8编码以独立于机器的方式将字符串写入基础输出流。 首先,将两个字节写入输出流,就像通过writeShort方法给出要跟随的字节数一样。该值是实际写入的字节数,而不是字符串的长度。按照长度,使用修改后的字符的UTF-8编码,依次输出字符串的每个字符。 (...)
writeBytes(String str)
和writeChars(String str)
方法都可以正常工作。