Search code examples
javastringfileseparatoris-empty

Separating words from a string in input textfile and printing it to output textfile line by line in Java


Yo, I got this code that prints all the string from a text file to another text file, line by line. It works perfectly but I'm afraid we're restricted on using .isEmpty(). Is there any other condition for the 2nd while statement other than .isEmpty()? like counting the line's size and decrementing it by the size of the word every loop? I tried line.length > 0, declared int size = line.length() - 1 and decrementing by size -= word.length(); but I still got errors having infinite loop.

Here's my code,

import java.io.*;

class fileStr{
    public static void main(String args[]){
        try{
            BufferedReader rw = new BufferedReader(new FileReader("inStr.txt"));
            PrintWriter sw = new PrintWriter(new FileOutputStream("outStr.txt"));
            String line = rw.readLine();
            while(line!=null){
                String word = line.substring(0,line.indexOf(" "));
                while(!word.isEmpty()){
                    sw.println(word);
                    line = line.substring(line.indexOf(" ") + 1) + " ";
                    word = line.substring(0,line.indexOf(" "));
                }
                line = rw.readLine();
            }
            rw.close();
            sw.close();
        }catch(Exception e){
            System.out.println("\n\tFILE NOT FOUND!");
        }
    }
}

Please help, thanks.


Solution

  • According to the docs isEmpty() returns true if and only if the String's length is zero. You can perform this exact same check pretty easily without using isEmpty():

    while(word.length() > 0){
        ....
    

    As for the failed tries to use length() - in order to help you there you should post some missing details, such as, the content of the file you're reading and on which line it fails.