You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java从文件初始化二维数组并按税则码汇总数据写入文件求助

任务需求与代码求助

任务说明

我是编程新手,需要完成一项Java任务:读取一个包含5列数据的TXT文件,列分别为描述、数量、重量、价格、税则码,列间以空格分隔。需按税则码对数据进行汇总,即统计每个税则码对应的总数量、总重量、总价格,并将结果写入文件。

输入数据示例

描述数量重量价格税则码
rubber20,33,084016920000
pen30,35,049608101000
pen20,22,59608101000
pencil50,246,39609101000
pencil30,184,89609101000

预期输出结果

描述数量重量价格税则码
rubber20,33,084016920000
pen50,57,549608101000
pencil80,4211,19609101000

我的尝试

我原本想通过二维数组存储数据并计算,但不知道具体怎么实现,写了两段错误代码:

第一段代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
import java.util.Scanner;
import java.util.Iterator;
import java.util.ArrayList;
import java.io.FileWriter;
import java.util.Arrays;
import java.io.*;

public class Mail {
    
    public static void main(String args[]) throws Exception{
           
          File file1 = new File("C: \"Test for java input.txt");
          if (file1.length() == 0) {  System.out.println("File is empty"); System.exit(0);}    
          FileInputStream fis = new FileInputStream(file1);
          byte[] byteArray = new byte[(int)file1.length()];
          fis.read(byteArray);
          String data = new String(byteArray);
          String[] stringArray = data.split("\r\n");
          System.out.println("Number of lines in the file are ::"+stringArray.length);
          fis.close();
          
        
          
          BufferedReader br = new BufferedReader (new FileReader ( "C: Test for java input.txt"));
          String line;
          char[][] maze = new char[stringArray.length][5];
                       
          while ((line = br.readLine() ) != null ){

                char[] row = line.toCharArray();
                    int x = 0;
                    for (int i = 0; i < row.length; i++) {
                    maze[x][i] = row[i];

                    System.out.print(maze[i]);
                    x++;
                    }
                    System.out.printf("%n");  //mention this
                }
          
          
          
          File file2 = new File("C:  \"Test for java output.txt");
            int text = stringArray.length;
     
            try (PrintWriter out = new PrintWriter(file2, StandardCharsets.UTF_8))
            {
                out.print(text);
                System.out.println("Successfully written data to the file");
            } catch (IOException e) {
                e.printStackTrace();
            }


}
}  

第二段尝试的代码片段:

BufferedReader br = new BufferedReader (new FileReader ( "C:Test for java input.txt"));
          String line;
          char[][] maze = new char[stringArray.length][5];
                       
          while ((line = br.readLine() ) != null ){

                char[] row = line.toCharArray();
                    int x = 0;
                    for (int i = 0; i < row.length; i++) {
                    maze[x][i] = row[i];

                    System.out.print(maze[i]);
                    x++;
                    }
                    System.out.printf("%n");  //mention this
                } 

解决方案

针对这个任务,使用HashMap存储税则码与汇总数据的映射会比二维数组更高效直观,同时创建一个类封装每个税则码的汇总信息,逻辑更清晰。以下是完整的可运行代码:

1. 汇总信息封装类

class ItemSummary {
    private String description;
    private int totalQuantity;
    private double totalWeight;
    private double totalPrice;
    private String tariffCode;

    public ItemSummary(String description, int quantity, double weight, double price, String tariffCode) {
        this.description = description;
        this.totalQuantity = quantity;
        this.totalWeight = weight;
        this.totalPrice = price;
        this.tariffCode = tariffCode;
    }

    // 累加同税则码的数量、重量、价格
    public void add(int quantity, double weight, double price) {
        this.totalQuantity += quantity;
        this.totalWeight += weight;
        this.totalPrice += price;
    }

    // getter方法,用于获取汇总数据
    public String getDescription() { return description; }
    public int getTotalQuantity() { return totalQuantity; }
    public double getTotalWeight() { return totalWeight; }
    public double getTotalPrice() { return totalPrice; }
    public String getTariffCode() { return tariffCode; }
}

2. 主处理类

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ItemSummaryProcessor {

    public static void main(String[] args) {
        String inputFilePath = "C:\\Test for java input.txt";
        String outputFilePath = "C:\\Test for java output.txt";

        // 用HashMap存储税则码对应的汇总数据,税则码作为唯一键
        Map<String, ItemSummary> summaryMap = new HashMap<>();

        // 读取输入文件并处理数据
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inputFilePath), StandardCharsets.UTF_8))) {
            String line;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty()) continue; // 跳过空行

                // 按空格拆分每一行数据
                String[] columns = line.split("\\s+");
                if (columns.length != 5) {
                    System.out.println("无效行,跳过:" + line);
                    continue;
                }

                // 解析每列数据,注意处理小数分隔符(逗号转点)
                String description = columns[0];
                int quantity = Integer.parseInt(columns[1]);
                double weight = Double.parseDouble(columns[2].replace(",", "."));
                double price = Double.parseDouble(columns[3].replace(",", "."));
                String tariffCode = columns[4];

                // 更新汇总数据
                if (summaryMap.containsKey(tariffCode)) {
                    summaryMap.get(tariffCode).add(quantity, weight, price);
                } else {
                    summaryMap.put(tariffCode, new ItemSummary(description, quantity, weight, price, tariffCode));
                }
            }
        } catch (IOException e) {
            System.err.println("读取文件失败:" + e.getMessage());
            e.printStackTrace();
            return;
        } catch (NumberFormatException e) {
            System.err.println("数值格式错误:" + e.getMessage());
            e.printStackTrace();
            return;
        }

        // 将汇总结果写入输出文件
        try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputFilePath), StandardCharsets.UTF_8))) {
            for (ItemSummary summary : summaryMap.values()) {
                // 将小数转回逗号分隔的格式,保持与输入一致
                String formattedWeight = String.format("%.2f", summary.getTotalWeight()).replace(".", ",");
                String formattedPrice = String.format("%.2f", summary.getTotalPrice()).replace(".", ",");

                // 拼接成输出行
                String outputLine = String.join(" ",
                        summary.getDescription(),
                        String.valueOf(summary.getTotalQuantity()),
                        formattedWeight,
                        formattedPrice,
                        summary.getTariffCode());
                pw.println(outputLine);
            }
            System.out.println("汇总结果已成功写入文件:" + outputFilePath);
        } catch (IOException e) {
            System.err.println("写入文件失败:" + e.getMessage());
            e.printStackTrace();
        }
    }
}

关键说明

  • HashMap的使用:税则码作为唯一键,能快速定位到同一税则码的汇总数据,避免二维数组的遍历查找,效率更高
  • 小数处理:输入数据用逗号作为小数分隔符,需要先转换为点才能用Java的数值解析方法,输出时再转回逗号
  • 资源管理:使用try-with-resources语法自动关闭文件流,避免资源泄漏
  • 异常处理:捕获文件读写和格式错误,提升程序的鲁棒性

内容的提问来源于stack exchange,提问作者Pavel Jefimovich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 12:59:56