-1

I have created a program that will scan a text file, switch certain characters, and print into another file. I created a program that changed "|" to "\t" AND "\n" to "". There is a run-time error saying, "Exception in thread "main" java.lang.NullPointerException at Nov5.main(Nov5.java:20)"

If anyone knows how to correct this error and get my program running, that would be great. Thanks so much!

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedWriter;

public class Nov5  
{

public static void main( String args[] )
{

    try
    {

        BufferedReader br = new BufferedReader(new FileReader( "OneRecord.fna" ));
        BufferedWriter bw = new BufferedWriter(new FileWriter( "OneLineRecord.faa" ));

        String line;
        { 
            while ((line = br.readLine () ) != null)
            line = line.replace ( '|' , '\t');
            String replacedString = line.replaceAll ("(\\n)", "");
            bw.write( line );

        }
        br.close();
        bw.close();
    }
    catch( IOException e )
    {
        System.out.println( "error" );
    }
}
}
Jørgen R
  • 10,568
  • 7
  • 42
  • 59
  • Note: you don't use `replacedString` (probably a typo). So your logic that removes `\n` has no effect. – ajb Nov 14 '14 at 01:00

2 Answers2

0

Add braces to your while loop so the statement is not terminated when replaceAll occurs

while ((line = br.readLine()) != null) { // increase scope

    line = line.replace('|', '\t');
    String replacedString = line.replaceAll("(\\n)", "");
    bw.write(line);
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

You have your opening brace { in the wrong place for your while loop.

Without braces following the while loop condition, only the first statement after it acts as the body of the loop. By the time you get to this line

String replacedString = line.replaceAll ("(\\n)", "");

the entire file has been read and line is null. Change

{
    while ((line = br.readLine () ) != null)

to

while ((line = br.readLine () ) != null) {
rgettman
  • 176,041
  • 30
  • 275
  • 357