How to save strings in individual lines in a text file



  • I'm preparing an automation script which can check spelling mistakes from a website and show me the misspelled words and prepare a list for the same. To do this, I need to split sentences to the individual words so that my script can check spellings.

    I'm opening URL's sequentially from a CSV file and copy-pasting all the content of each URL to a separate text file. Then I read that newly created text file and try to separate all the words into individual strings. Once I have the file with one word on each line, it will be fed to my spell check script.

    For example, suppose a website has the content "Hello World". My code will create a new text file named 1.txt which will contain the text "Hello World". From that I'm trying to read the text file and create a new file named 1_word_by_word.txt which contains "Hello" in the 1st line and "World" in the 2nd.

    Somehow I'm printing only the last word of the sentence. But when I send it to the console it's printing properly.

    My code is:

    while(scan.hasNextLine())
    {
        System.out.println(scan.next());
        String word_by_word = scan.next();
        String TestFile_2 = "Word_By_Word.txt";
        File FC_2 = new File(TestFile_2);
        FC_2.createNewFile();
    
        //Create Object of java FileWriter and BufferedWriter class.
        //Writing In to file.
        FileWriter FileWriter_2 = new FileWriter(TestFile_2);
        FileWriter_2.write(word_by_word);
        FileWriter_2.flush();
        FileWriter_2.close();
    }
    

  • QA Engineer

    You would need to modify your code to something like this:

    File FC_2 = new File(TestFile_2);
    FC_2.createNewFile();
    FileWriter FileWriter_2 = new FileWriter(TestFile_2);
    while(scan.hasNextLine()) {
        String word_by_word = scan.next();
        System.out.println(word_by_word);
        FileWriter_2.write(word_by_word+"\n");
    
    }
    FileWriter_2.flush();
    FileWriter_2.close();
    

    You are iterating line-by-line and writing words one at a time into the file. In the while loop of your code, a new instance of File and FileWriter is being created for every line. This is not needed. What is happening in your case is that the older file is getting overwritten every time a new line is encountered.

    Also, the print statement that you have contains a scan.next() as a result of which word_by_word is reading only the next word (and missing the first word of that line).

    In addition, if you want every word captured to be entered into a new line of the output file, then add a "\n" to your FileWriter part of the code. Note that the last line will just have a newline character.

    Hope this helps! 🙂

    Although, I do agree with Kate here. This question does not have anything to do with testing/automation.


Log in to reply
 

Suggested Topics