inputSplit.java分析

本文介绍了Hadoop中InputSplit的概念及其核心方法。InputSplit代表了将由单一Mapper处理的数据分割。文章详细解释了如何通过getLength获取分割大小,并通过getLocations获取数据所在节点的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.hadoop.mapreduce;

import java.io.IOException;

import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.RecordReader;

/**
 * <code>InputSplit</code> represents the data to be processed by an 
 * individual {@link Mapper}. 
 *代表将要被mapper独自处理的分割文件。
 * <p>Typically, it presents a byte-oriented view on the input and is the 
 * responsibility of {@link RecordReader} of the job to process this and present
 * a record-oriented view.
 * 
 * @see InputFormat
 * @see RecordReader
 */
public abstract class InputSplit {
  /**
   * Get the size of the split, so that the input splits can be sorted by size.
   * 得到分割文件的大小 这样分割文件可以按大小排序
   * @return the number of bytes in the split
   * @throws IOException
   * @throws InterruptedException
   */
  public abstract long getLength() throws IOException, InterruptedException;

  /**
   * Get the list of nodes by name where the data for the split would be local.
   * The locations do not need to be serialized.
   * 获得 分割文件将要本地化哪里的节点列表 ,本地化不需要序列化。
   * @return a new array of the node nodes.
   * @throws IOException
   * @throws InterruptedException
   */
  public abstract 
    String[] getLocations() throws IOException, InterruptedException;
}

package BeiKe; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class CleanHouse1 { // 自定义InputFormat处理完整JSON数组 public static class WholeFileInputFormat extends FileInputFormat<Text, Text> { @Override public RecordReader<Text, Text> createRecordReader(InputSplit split, TaskAttemptContext context) { return new WholeFileRecordReader(); } @Override protected boolean isSplitable(JobContext context, Path file) { return false; // 禁止文件分割 } } // 自定义RecordReader读取整个文件 public static class WholeFileRecordReader extends RecordReader<Text, Text> { private Text key = new Text(); private Text value = new Text(); private boolean processed = false; @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException { FileSplit fileSplit = (FileSplit) split; Path path = fileSplit.getPath(); FileSystem fs = path.getFileSystem(context.getConfiguration()); try (FSDataInputStream in = fs.open(path); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } value.set(sb.toString()); } } @Override public boolean nextKeyValue() { if (!processed) { key.set("json_array"); processed = true; return true; } return false; } @Override public Text getCurrentKey() { return key; } @Override public Text getCurrentValue() { return value; } @Override public float getProgress() { return processed ? 1.0f : 0.0f; } @Override public void close() {} } // Mapper类处理JSON数组 public static class JsonMapper extends Mapper<Text, Text, Text, Text> { // 检查是否包含无效值 private boolean containsNullValue(JSONObject json) { for (String key : json.keySet()) { Object value = json.get(key); if (value instanceof String) { String strValue = (String) value; if ("无".equals(strValue) || "暂无信息".equals(strValue)) { return true; } } } return false; } // 处理无效值 private void processNull(JSONObject json) { // 首先检查并过滤单价字段 String price = json.optString("单价(元/平方米)", ""); if (price.isEmpty() || "暂无信息".equals(price) || "无".equals(price) || "NaN".equals(price)) { return; // 直接返回,跳过此记录 } // 重命名字段 json.put("元/平方米", json.remove("单价(元/平方米)")); // 然后检查其他字段是否包含无效值 if (containsNullValue(json)) { return; // 包含无效值,跳过此记录 } } @Override protected void map(Text key, Text value, Context context) throws IOException, InterruptedException { try { String jsonString = value.toString().trim(); JSONArray jsonArray = new JSONArray(jsonString); for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); // 创建原始副本用于错误处理 JSONObject originalJson = new JSONObject(json.toString()); // 处理无效值 processNull(json); // 如果处理后json为空或包含无效值,则跳过 if (json.length() == 0 || containsNullValue(json)) { continue; } // 输出有效记录 - 使用固定键确保所有数据进入同一个Reducer context.write(new Text("all_records"), new Text(json.toString())); } } catch (Exception e) { System.err.println("JSON处理错误: " + e.getMessage()); System.err.println("错误数据: " + value.toString()); } } } // Reducer类构建完整JSON数组 public static class JsonReducer extends Reducer<Text, Text, Text, Text> { @Override protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { // 收集所有JSON对象 List<JSONObject> jsonObjects = new ArrayList<>(); for (Text value : values) { jsonObjects.add(new JSONObject(value.toString())); } // 构建完整JSON数组 StringBuilder result = new StringBuilder("[\n"); for (int i = 0; i < jsonObjects.size(); i++) { // 格式化JSON对象输出 JSONObject obj = jsonObjects.get(i); result.append(" {\n"); // 添加每个字段并格式化 String[] keys = obj.keySet().toArray(new String[0]); for (int j = 0; j < keys.length; j++) { String field = keys[j]; result.append(" \"").append(field).append("\": "); Object val = obj.get(field); if (val instanceof String) { result.append("\"").append(val).append("\""); } else { result.append(val); } if (j < keys.length - 1) { result.append(","); } result.append("\n"); } result.append(" }"); if (i < jsonObjects.size() - 1) { result.append(","); } result.append("\n"); } result.append("]"); // 输出完整JSON数组 context.write(null, new Text(result.toString())); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "JSON Array Processor"); job.setJarByClass(CleanHouse.class); job.setInputFormatClass(WholeFileInputFormat.class); job.setMapperClass(JsonMapper.class); job.setReducerClass(JsonReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }上述代码运行结果如下[root@hadoop01 software]# hadoop jar CleanHouse2.jar /out1/part-r-00000 /out2 Exception in thread "main" java.lang.NoClassDefFoundError: BeiKe/CleanHouse at BeiKe.CleanHouse1.main(CleanHouse1.java:205) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.hadoop.util.RunJar.run(RunJar.java:221) at org.apache.hadoop.util.RunJar.main(RunJar.java:136) Caused by: java.lang.ClassNotFoundException: BeiKe.CleanHouse at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 7 more
最新发布
06-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值