1

I have a text file list of thousands of String (3272) and I want to put them each into a slot of an Array so that I can use them to be sorted out. I have the sorting part done I just need help putting each line of word into an array. This is what I have tried but it only prints the last item from the text file.

public static void main(String[] args) throws IOException 
{
    FileReader fileText = new FileReader("test.txt");
    BufferedReader scan = new BufferedReader (fileText);
    String line;
    String[] word = new String[3272];
    
    Comparator<String> com = new ComImpl();
    
    while((line = scan.readLine()) != null)
    {
        for(int i = 0; i < word.length; i++)
        {
            word[i] = line;
        }
    }
    
    
    Arrays.parallelSort(word, com);

    
    for(String i: word)
    {
        System.out.println(i);
    }
}
greg-tumolo
  • 698
  • 1
  • 7
  • 30

3 Answers3

1

Each time you read a line, you assign it to all of the elements of word. This is why word only ends up with the last line of the file.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Replace the while loop with the following code.

    int next = 0;
    while ((line = scan.readLine()) != null) word[next++] = line;
greg-tumolo
  • 698
  • 1
  • 7
  • 30
0

Try this.

Files.readAllLines(Paths.get("test.txt"))
    .parallelStream()
    .sorted(new ComImpl())
    .forEach(System.out::println);