0

I'm trying to write a program, which reads text from a file that is specified by the user. Now, this program should detect an empty line.

This is what I have unsuccessfully tried:

public static void editFile(String filePath) throws FileNotFoundException, IOException {
    file = new File(filePath);
    if(file.exists()) {
        fileRead = new FileReader(file);

        bufferedReader = new BufferedReader(fileRead);

        String line = bufferedReader.readLine();
        System.out.println(line);
        while(line != null) {
            line = bufferedReader.readLine();
            if(line == "") {
                //line = null;
                System.out.println("a");
            }
            System.out.println(line);
        }
    }
}

To be more clear:

If I'm passing in a text file with for example this text:

test1
test2

test3

test4

it should print 2 a's in the console because of the empty spaces, but it doesn't.

Thank you for your time, I am glad for any suggestion you may have.

C1pher
  • 1,933
  • 6
  • 33
  • 52
notthisname
  • 13
  • 1
  • 4

3 Answers3

1

This is because the comparison is wrong. You can't use == to compare two strings, you need to use the equals method:

if(line.equals(""))

Since you are checking for empty string, you can also write

if(line.isEmpty())

How do I compare strings in java?

Community
  • 1
  • 1
BackSlash
  • 21,927
  • 22
  • 96
  • 136
1

BackSlash is entirely correct, and has answered your question. I'd like to add that your code has some errors:

  • You're not closing the Reader
  • You're not testing the first line for blank
  • You're processing the null value when reaching EOF

The following corrects these errors.

public static void editFile(String filePath) throws IOException
{
    File file = new File(filePath);
    if (file.exists())
    {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        try
        {
            String line;
            while ((line = bufferedReader.readLine()) != null)
            {
                if (line.isEmpty())
                {
                    //line = null;
                    System.out.println("a");
                }
                System.out.println(line);
            }
        } finally {
            bufferedReader.close();
        }
    }
}

Output is:

test1
test2
a

test3
a

test4

Note: You're still printing the blank line in addition to the "a".

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

What you're doing wrong is that you're comparing the variable itself, not its value with a null string. Generally there are built-in functions in the string class that return true & false for checking if it's == with something.

if(line.equals("")) { ... }

Or you can just use any alternative way.

Alaa Salah
  • 1,047
  • 3
  • 12
  • 28