Home > Back-end >  Writing List<String> to a text file in Java with FileWriter() - saves only first word
Writing List<String> to a text file in Java with FileWriter() - saves only first word

Time:09-02

I have this code which creates a list of words: [the, of, value, v, key, to, given, a, k, map]

I want to save this list into a stopwordslist.txt file.

With the code below it writes only the first word, 'the', into this file.


    private static List<String> StopWordsFile(Map<String, String> lemmas) {

// Map 'counts' stores each word and its frequency
        Map<String, Integer> counts = new HashMap<>();

// 'corpus' stores for all the individual words
        ArrayList<String> corpus = new ArrayList<String>();

        for (String line : lemmas.values()) {
            for (String word : line.toLowerCase().trim().split("[\\p{Punct}\\d\\s] ")) {
                if (counts.containsKey(word)) {
                    counts.put(word, counts.get(word)   1);
                } else {
                    counts.put(word, 1);
                }
            }

        }
// Create a list to store all the words with their frequency and sort it by values.

        List<Map.Entry<String, Integer>> list = new ArrayList<>(counts.entrySet());
        list.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));

        List<String> stopwordslist = new ArrayList<>();
        for (Map.Entry<String, Integer> e : list)
            stopwordslist.add(e.getKey());

        // return top 10% most frequent words
        List<String> topTenPercentlist = new ArrayList<>(stopwordslist.subList(0, (int) (0.10 * list.size())));

        System.out.println("List after sorting: "   topTenPercentlist);

        // write the list into a .txt file
        try {
            FileWriter writer = new FileWriter("stopwordslist.txt");
            
            for(String word: topTenPercentlist) {
                writer.write(word   System. lineSeparator());       
                writer.close();    
                System.out.println("Data Written to the text file successfully");
                }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Saving to a text file failed...");
        }
        
            
        return topTenPercentlist;

    }

I have also tried this try-catch block, and it prints every word multiple times.

    try {
                        
            BufferedWriter writer = new BufferedWriter(new FileWriter("outputlist3.txt"));
    //      FileWriter writer = new FileWriter("outputlist2.txt");
            
            for(String word: topTenPercentlist) {
        //      writer.write(word   System. lineSeparator());
                for(int i = 0; i <  topTenPercentlist.size(); i  ) {
                    writer.write(word);
                    writer.newLine();
            
                }
                   
        //  System.out.println("Data Written to the text file successfully");
                }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Saving to a text file failed...");
        }

how can I do it correctly?

CodePudding user response:

Don't close the file until you are finished writing

    try {
        FileWriter writer = new FileWriter("stopwordslist.txt");
        
        for(String word: topTenPercentlist) {
            writer.write(word   System. lineSeparator());
            //REMOVE THE BELOW       
            //writer.close();    
            System.out.println("Data Written to the text file successfully");
        }
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Saving to a text file failed...");
    }
  • Related