Some amendment of the data in txt file. I have tried the suggested code but Im not successfully write it again in the txt file with this format.I've tried the collection.sort but it write the data in long line.
My txt file contain these data:
Monday
Jessica Run 20mins
Alba Walk 20mins
Amy Jogging 40mins
Bobby Run 10mins
Tuesday
Mess Run 20mins
Alba Walk 20mins
Christy Jogging 40mins
Bobby Run 10mins
How can I sort those data in ascending order and store it again in txt file after sorting?
Monday
Alba Walk 20mins
Amy Jogging 40mins
Bobby Run 10mins
Jessica Run 20mins
Tuesday
Alba Walk 20mins
Bobby Run 10 mins
Christy Jogging 40mins
Mess Run 20mins
Jessica Run 20mins
Although there's no straightforward way to sort a text file, we can achieve the same net result by doing the following: 1) Use the FileSystemObject to read the file into memory; 2) Sort the file alphabetically in memory; 3) Replace the existing contents of the file with the sorted data we have in memory.
sort() method is present in java. util. Collections class. It is used to sort the elements present in the specified list of Collection in ascending order.
Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.
Here's something I came up with:
import java.io.*;
import java.util.*;
public class Sort {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("fileToRead"));
Map<String, String> map=new TreeMap<String, String>();
String line="";
while((line=reader.readLine())!=null){
map.put(getField(line),line);
}
reader.close();
FileWriter writer = new FileWriter("fileToWrite");
for(String val : map.values()){
writer.write(val);
writer.write('\n');
}
writer.close();
}
private static String getField(String line) {
return line.split(" ")[0];//extract value you want to sort on
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With