Here you can find the source of sort(String inFile, int keyIndex, String outFile)
public static void sort(String inFile, int keyIndex, String outFile)
//package com.java2s; /*// w ww . java 2s. c o m * (C) Copyright 2017 Shuangyan Liu * Shuangyan.Liu@open.ac.uk * Knowledge Media Institute * The Open University, United Kingdom * * Licensed 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. * */ import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; public class Main { public static void sort(String inFile, int keyIndex, String outFile) { TreeMap<Integer, ArrayList<String>> tmap = new TreeMap<>(); try { List<String> list = Files.readAllLines(Paths.get(inFile), StandardCharsets.UTF_8); String prevKey = ""; ArrayList<String> sameKeyLines = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { String[] str = list.get(i).split("\t"); String currentKey = str[keyIndex]; if (prevKey.isEmpty()) prevKey = currentKey; if (!tmap.containsKey(Integer.valueOf(currentKey))) { if (currentKey.equalsIgnoreCase(prevKey)) { sameKeyLines.add(list.get(i)); } else { tmap.put(Integer.valueOf(prevKey), sameKeyLines); prevKey = currentKey; sameKeyLines = new ArrayList<>(); sameKeyLines.add(list.get(i)); } } } tmap.put(Integer.valueOf(prevKey), sameKeyLines); BufferedWriter bw = new BufferedWriter(new FileWriter(outFile, false)); for (Integer k : tmap.navigableKeySet()) { for (String line : tmap.get(k)) { bw.write(line); bw.write(System.lineSeparator()); } } bw.close(); } catch (IOException e) { } } }