Search code examples
javabufferedreaderfilereader

FileReader and BufferedReader


I have 3 methods

  1. for open file
  2. for read file
  3. for return things read in method read

this my code :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication56;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author x
 */
public class RemoteFileObjectImpl extends java.rmi.server.UnicastRemoteObject  implements RemoteFileObject
{
    public RemoteFileObjectImpl() throws java.rmi.RemoteException {
        super();
    }

    File f = null;
    FileReader r = null;
    BufferedReader bfr = null;

    String output = "";
    public void open(String fileName) {
        //To read file passWord
        f = new File(fileName);
    }
    public String readLine() {
        try {
            String temp = "";
            String newLine = System.getProperty("line.separator");
            r = new FileReader(f);
            while ((temp = bfr.readLine()) != null) {
                output += temp + newLine;
                bfr.close();
            }
        }
        catch (IOException ex) {
           ex.printStackTrace();
        }

        return output;
    }

    public void close() {
        try {
            bfr.close();
        } catch (IOException ex) {
        }
    }

    public static void main(String[]args) throws RemoteException{
        RemoteFileObjectImpl m = new RemoteFileObjectImpl();
        m.open("C:\\Users\\x\\Documents\\txt.txt");
        m.readLine();
        m.close();
    } 
}

But it does not work.


Solution

  • What do you expect it to do, you are not doing anything with the line you read, just

    m.readLine();
    

    Instead:

    String result = m.readLine();
    

    or use the output variable that you saved.

    Do you want to save it to a variable, print it, write it to another file?

    Update: after your update in the comments: Your variable bfr is never created/initialized. You are only doing this:

    r = new FileReader(f);
    

    so bfr is still null.

    You should do something like this instead:

    bfr = new BufferedReader(new FileReader(f));