Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package languagesort;
- import java.io.*;
- import java.util.*;
- public class LanguageSort {
- // Main method
- public static void main(String[] args) throws Exception {
- // reads the lines of txt from location
- String[] Languages = readLines("unsorted.txt");
- // display the lines that are in the string array
- displaysLines(Languages);
- // sorts the string array in ABD order
- sortStringArray(Languages);
- // displays the now sorted string array
- displaysLines(Languages);
- // writes the string array to a specified path
- writeLines("tutorials.txt",Languages);
- }
- // Returns a string aray from a file at specified path
- public static String[] readLines(String Path) throws Exception {
- File unsortedLanguages = new File("unsorted.txt");
- Scanner FileReader;
- FileReader = new Scanner(unsortedLanguages);
- String[] tempArray = new String[100];
- int count = 0;
- while (FileReader.hasNextLine()) {
- tempArray[count] = FileReader.nextLine();
- count++;
- }
- String[] lines = new String[count];
- System.arraycopy(tempArray, 0, lines, 0, count);
- FileReader.close();
- return lines;
- }
- // Displays a string array line by line
- public static void displaysLines(String[] lines) {
- for (String line : lines) System.out.println(line);
- System.out.println();
- }
- // Sorts the specified string array in ABC order (BubbleSort)
- public static void sortStringArray(String[] lines) {
- boolean swapped;
- String temp;
- do {
- swapped = false;
- for(int i=0; i < (lines.length - 1) ; i++) {
- if(lines[i+1].compareTo(lines[i]) < 0) {
- temp = lines[i];
- lines[i] = lines[i+1];
- lines[i+1] = temp;
- swapped = true;
- }
- }
- } while (swapped);
- }
- // Writes a string array to an output file, each element is a line
- public static void writeLines(String Path, String[] lines) throws Exception {
- File tutorials = new File(Path);
- PrintWriter output;
- output = new PrintWriter(tutorials);
- for (String line: lines) output.println(line);
- output.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment