-2
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();
        }

    }
}

This is my code. I am not getting a proper result. The file contains 10 columns, and the 5th column is 'city'. There are 10 different cities in a file. I need to split each city a separate file.

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

0

You are not calling close on all the FileWriter and hence the data may not get flushed to the file.

See FileWriter is not writing in to a file

At the end of the processing,

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

There is a bug in your code. You need to move the statements after the if (isFirst) block into the else block. Else, it will create a city.txt file too.

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
  • thanks a lot its working... i am very new to java.. i was little bit confused..thanks for reply... – farhana fatima Aug 28 '18 at 10:26
  • @farhanafatima If this has solved your problem, you can consider accepting it https://stackoverflow.com/help/someone-answers – Thiyagu Aug 28 '18 at 10:32