How to read, sort and write a new file with a specific text file?
A great question, isn't it?
What about a Java example to show how to read a file, sorting it and writing the result into a new text file?
Let's see that in this tutorial with a classic exercise, to manipulate inputs and outputs files.
Create your project with a package named badprog.
Inside this package, create your Main.java.
Then add a file with letters or words inside (one word by line):
The main advantage of a TreeMap is that you can use it to sort a file.
Indeed, just pass elements to it and they'll be sorted.
A second advantage is that you can tell the TreeMap wich sort of sort you would like to have.
In our case, we've chosen the French locale to handle accents thanks to the the Collator class.
And last but not least, the program will remove all multi elements (each element is now unique in the list).
hello Hello â é è ë ê a Ë Ê É È a A a ¾ A ä Ä É AE ae B bb  À e y Ä Æ Hell hell HELL
package badprog; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.text.Collator; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.TreeMap; public class Main { private static String fileToRead = "raw.txt"; private static String fileToWrite = "clean.txt."; private static String whereAreFiles = "./src/badprog/"; private static String endOfLine = "\n"; /** * The main function. * @param args */ public static void main(String[] args) throws Exception { String line = null; BufferedReader fileReader = new BufferedReader(new FileReader(whereAreFiles + fileToRead)); FileWriter fileWriter = new FileWriter(whereAreFiles + fileToWrite); Map<String, String> map = new LinkedHashMap<String, String>(); map = sortThisByKey(map); while((line = fileReader.readLine()) != null) { map.put(line, line); } fileReader.close(); for (String data : map.values()){ fileWriter.write(data + endOfLine); } fileWriter.close(); } /** * Sorts the whole map by case insensitive order. * @param theMap * @return */ private static Map<String, String> sortThisByKey(Map<String, String> theMap){ TreeMap<String, String> result = new TreeMap<String, String>(Collator.getInstance(Locale.FRENCH)); result.putAll(theMap); return result; } }
Compile your code and to see the new file, you have to refresh your badprog package (or your whole project) > Right click > Refresh.
¾ a A À â Â ä Ä ae AE Æ B bb e é É è È ê Ê ë Ë hell Hell HELL hello Hello y
There were 33 lines in the raw.txt and now 28 in the clean.txt because duplicated elements have been removed.
The file is now sorted but without sensitive case though.
Free to you to implement it.
An easy but helpful tutorial.
Good job, you've made it!
Add new comment