我想读取一个文本文件并根据列值拆分它

I want to read a text file and split it based on column value

public class FileSplitter2 {

    public static void main(String[] args) throws IOException {

        String filepath = "D:\temp\test.txt";

        BufferedReader reader = new BufferedReader(new FileReader(filepath));
        String strLine;
        boolean isFirst = true;
        String strGroupByColumnName = "city";
        int positionOgHeader = 0;
        FileWriter objFileWriter;
        Map<String, FileWriter> groupByMap = new HashMap<String, FileWriter>();
        while ((strLine = reader.readLine()) != null) {
            String[] splitted = strLine.split(",");
            if (isFirst) {
                isFirst = false;
                for (int i = 0; i < splitted.length; i++) {
                    if (splitted[i].equalsIgnoreCase(strGroupByColumnName)) {
                        positionOgHeader = i;
                        break;
                    }
                }
            }
            String strKey = splitted[positionOgHeader];
            if (!groupByMap.containsKey(strKey)) {
                groupByMap.put(strKey, new FileWriter("D:/TestExample/" + strKey + ".txt"));
            }
            FileWriter fileWriter = groupByMap.get(strKey);
            fileWriter.write(strLine);
        }
        for (Map.Entry<String,FileWriter> entry : groupByMap.entrySet()) {
        entry.getKey();
        }

    }
}

这是我的代码。我没有得到正确的结果。该文件包含 10 列,第 5 列是 'city'。一个文件中有 10 个不同的城市。我需要将每个城市拆分成一个单独的文件。

您没有在所有 FileWriter 上调用 close,因此数据可能不会刷新到文件中。

处理结束时,

 groupByMap.values().forEach(fileWriter -> {
        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace(); //Add appropriate error handling
        }
    });

您的代码中存在错误。您需要将 if (isFirst) 块之后的语句移动到 else 块中。否则,它也会创建一个 city.txt 文件。