Skip to content

Instantly share code, notes, and snippets.

@parameshjava
Created October 27, 2018 04:39
Show Gist options
  • Save parameshjava/d8b0fbfbdb16ce25dfd49bf8d315835d to your computer and use it in GitHub Desktop.
Save parameshjava/d8b0fbfbdb16ce25dfd49bf8d315835d to your computer and use it in GitHub Desktop.
CSV File operation
package com.sample;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class CsvOperations {
public static void sort(String filepath) throws IOException {
// Fetch the the first line from a file
List<String> lines = Files.lines(Paths.get(filepath)).collect(Collectors.toList());
// Store the first line as it is from the file as its just a header
String firstLine = lines.get(0);
// Remove the first line as already stored
lines.remove(0);
// Sort the lines with the list
lines.sort(new Comparator<String>() {
@Override
public int compare(String currentLine, String nextLine) {
// Split the lines with comma separator
String[] currLineWords = currentLine.split(",");
String[] nextLineWords = nextLine.split(",");
// Compare first line word with second line word in their respective cell position in the CSV
for (int index = 0; index < currLineWords.length; index++) {
// Compare cells in the respective position, if not same rearrange the lines
int comparison = currLineWords[index].compareTo(nextLineWords[index]);
if (comparison != 0) {
return comparison;
}
}
return 0;
}
});
// Extract directory location from file path
String directory = filepath.substring(0, filepath.lastIndexOf(File.separator));
// Append _sorted to the file
String fileName = filepath.replace(directory + File.separator, "").replace(".", "_sorted.");
// Write the sorted file in the same location (here using try with resource to close the writer once the write operation successful)
try (FileWriter writer = new FileWriter(new File(directory + File.separator + fileName))) {
// Write first line as it is
writer.write(firstLine);
// Iterate each line and write to the file
lines.forEach(line -> {
try {
writer.write("\n");
writer.write(String.join(",", line));
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
public static void main(String[] args) throws IOException {
String filePath = "C:\\PARAMESH\\Interns\\Workspace\\Samples\\src\\com\\sample\\sample.csv";
sort(filePath);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment