Home > Mobile >  Why i got a null message when retrieveng an string line from a file in java
Why i got a null message when retrieveng an string line from a file in java

Time:07-14

I tried to retrieve a single line of text from a text file in java, and indeed i got what i expect but at the end it adds a null reference, but i don't know why. here my code:

public class EncryptDecryptFile {


public void writeDecryptionFile(String message) {

    File f;
    FileWriter writeArchive;

    try {

        f = new File("C:\\Users\\Dell\\Training\\DecryptionFile.txt");
        writeArchive = new FileWriter(f);
        BufferedWriter bw = new BufferedWriter(writeArchive);
        PrintWriter text = new PrintWriter(bw);

        text.write(message "\n");
        text.close();
        bw.close();

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }

}

public String readEncryptionFile() {

    File file = new File("C:\\Test\\EncryptionFile.txt");
    
    String line = "";
    
        try (
                BufferedReader br = new BufferedReader(new FileReader(file))) {
                
            
            while (true) {
               
                line = br.readLine();
                if (line != null) {
                    
                    System.out.print(line);
                    
                } else {
                    
                    break;
                }
            }
        
    } catch (IOException e) {
     
        e.printStackTrace();
    
    }   
    
    return line;

}

public static void main(String[] args) {

    EncryptDecryptFile file = new EncryptDecryptFile();
    file.writeDecryptionFile("Hello World!!!");
    System.out.println(file.readEncryptionFile());

}

}

The result is as follows

Hello World!!! null

Where is that null coming from ?

I appreciate any help :(

CodePudding user response:

You are returning line and printing it at the end of System.out.println(file.readEncryptionFile()); at that time it must be null (or the loop would not end). Solution, don't print it. Just do

file.readEncryptionFile();

Note: You also print with-in readEncryptionFile()

CodePudding user response:

Do not do

System.out.println(file.readEncryptionFile());

You are already printing it out in this method, so just calling

file.readEncryptionFile();

should suffice.

Of course you do not need to return a String from this method.

Alternative in the readEncryptionFile, create a StringBuilder Object and append to that if the line is not null, then return the String of the StringBuilder Object.

  •  Tags:  
  • java
  • Related