为什么用mapFIle不能正常打印
问题描述:
这里是SequenceFile,可以打印出文件的内容
但是改了一下代码,就没有打印出来
相关代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | package com.imooc.mr; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.MapFile; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.Text; import java.io.File; /** * 小文件解决方案之MapFile */ public class SmallFileMap { public static void main(String[] args) throws Exception { //生成MapFile文件 write( "D:\\samllFile" , "/mapFile" ); //读取MapFile文件 read( "/mapFile" ); } /** * 生成MapFile文件 * @param inputDir 输入目录-window目录 * @param outputDir 输出目录-hdfs目录 * @throws Exception */ private static void write(String inputDir,String outputDir) throws Exception { //创建一个配置对象 Configuration conf = new Configuration(); //指定HDFS的地址 conf.set( "fs.defaultFS" , "hdfs://bigdata01:9000" ); //获取操作HDFS的对象 FileSystem fileSystem = FileSystem.get(conf); //删除HDFS上的输出文件 fileSystem.delete( new Path(outputDir), true ); /*构造opt数组,有两个参数 第一个是key的类型 第二个是value的类型 */ SequenceFile.Writer.Option[] opts = new SequenceFile.Writer.Option[]{ MapFile.Writer.keyClass(Text.class), MapFile.Writer.valueClass(Text.class) }; //创建了一个witer实例 MapFile.Writer writer = new MapFile.Writer(conf, new Path(outputDir), opts); //指定需要压缩的文件目录 File inputDirPath = new File(inputDir); if (inputDirPath.isDirectory()) { //获取目录中的文件 File[] files = inputDirPath.listFiles(); //迭代文件 for (File file : files) { //获取文件的全部内容 String content = FileUtils.readFileToString(file, "UTF-8"); //获取文件名 String fileName = file.getName(); Text key = new Text(fileName); Text value = new Text(content); writer.append(key,value); } } writer.close(); } /** * 读取MapFile文件 * @param inputDir MapFile文件路径 * @throws Exception */ public static void read(String inputDir) throws Exception{ //创建一个配置对象 Configuration conf = new Configuration(); //指定HDFS的地址 conf.set( "fs.defaultFS" , "hdfs://bigdata01:9000" ); //创建阅读器 MapFile.Reader reader = new MapFile.Reader( new Path(inputDir), conf); Text key = new Text(); Text value = new Text(); //循环读取数据 while (reader.next(key, value)) { //输出文件名称 System.out.print( "文件名:" +key.toString()+ "," ); //输出文件内容 System.out.println( "文件内容:" + value.toString()); } reader.close(); } } |
5
收起
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧