0

My code order words from test.txt first Aphabeticly then by length and copies them in sort.txt. Words in test.txt looks like this:

  • word1
  • word5
  • word2
  • word6
  • word3
  • word4

so each word in its own line. The problem i am facing is lets say i have a word in test.txt that has 1 or more empty spaces before a word. I need that empty space to be removed. Or 1 or more spaces after a word.

EXAMPLE: lets say this is test.txt (* meaning space bar, so 1 or more empty spaces)

  • **word1
  • word5**
  • **word2
  • ****word6
  • word3*****
  • word4***

What i need sort.txt to look like is

  • word1
  • word2
  • word3
  • word4
  • word5

So without those empty spaces (marked as *). As you can see i am gettin well formated sort.txt which is ok and it works i just need to remove thos * or empty spaces so any ideas how?

package test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class sort {
public static class MyComparator implements Comparator<String>{
    @Override
    public int compare(String o1, String o2) {  
      if (o1.trim().length() > o2.trim().length()) {
         return 1;
      } else if (o1.trim().length() < o2.trim().length()) {
         return -1;
      }
      return o1.compareTo(o2);
    }
}
public static void main(String[] args) throws Exception {

    String inputFile = "test.txt";
    String outputFile = "sort.txt";

    FileReader fileReader = new FileReader(inputFile);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String inputLine;
    List<String> lineList = new ArrayList<String>();
    while ((inputLine = bufferedReader.readLine()) != null) {
        lineList.add(inputLine);
    }

    Collections.sort(lineList,String.CASE_INSENSITIVE_ORDER);
    Collections.sort(lineList, new MyComparator()); 

    FileWriter fileWriter = new FileWriter(outputFile);
    PrintWriter out = new PrintWriter(fileWriter);
    FileWriter Fw = new FileWriter(outputFile);
    PrintWriter pw = new PrintWriter(Fw);
    for (String outputLine : lineList) {
        if (!"".equals(outputLine.trim()))
            out.println(outputLine);        }       
    out.flush();
    out.close();
    fileWriter.close();

}
}
Rok Ivartnik
  • 137
  • 5
  • 17

1 Answers1

1

You're already using String.trim() in your Comparator.

Just use it as well when you add the lines to your Lists:

while ((inputLine = bufferedReader.readLine()) != null) {
   lineList.add(inputLine.trim());
}

You may even get to remove it from the Comparator if you're not reusing it somewhere else.

Mena
  • 47,782
  • 11
  • 87
  • 106