BufferedReader已初始化但readLine返回null?

时间:2014-12-19 11:18:19

标签: java file inputstream bufferedreader fileinputstream

我有一个类measurementFile,其构造函数发布在下面。在具有File_IO_03方法的类main中,我实例化了上述类的对象,但是当我尝试readLine使用mf.getbR.readLine时,控制台显示为null。

要注意:mf是前面提到的类的对象,getbR()是该类中应该返回初始化bufferedReader object的方法。

以下是我尝试使用bufferedReader

读取某个文件的行

代码

**File_IO_03**:

    File f = new File(path);
    MeasurementFile mf = new MeasurementFile(f, MeasurementFile.ENCODING_ISO_8859_1);

    if ( (mf.getiS() == null) || (mf.getbR() == null) ) {
        System.out.println("either iS or bR is null");
    }else {
        System.out.println("both iS or bR are initialised"); // successful
        System.out.println("path: " + mf.getFile().getAbsolutePath());// displayed
        System.out.println("" + mf.getbR().readLine()); // this returns null
        System.out.println("total lines in the file: " + mf.getTotalLines());// successful
        readLines(mf, 4);
        //readLines(mf, 6);
        //continueReading(mf);
    }

    private static void readLines(MeasurementFile mf, int lines) throws IOException {
    // TODO Auto-generated method stub
    /*InputStream is = new FileInputStream(mf.getFile());
    mf.setiS(is);
    BufferedReader br = new BufferedReader(new InputStreamReader(mf.getiS()));
    mf.setbR(br);*/

    String line;
    int linecounter = 0;

    while ((line = mf.getbR().readLine()) != null) {
        System.out.println("current line read: " + line);
        if (++linecounter == lines) {
            mf.getbR().mark(0);
            System.out.println("mark set at linecounter: " + linecounter + "lines: " + lines);
            break;
        }
    }
}

MeasurementFile Class_构造函数

    public MeasurementFile(File file, Charset encoding) throws IOException {
    this.setFile(file);

    //if (this.myFile.setReadOnly()) 
    this.getFile().setReadable(true);
    this.getFile().setWritable(true);

    if (this.getiS() == null) {
        this.iS = new FileInputStream(this.getFile());
        this.setiS(this.iS);
    }
    if (this.getbR() == null) {
        this.bR = new BufferedReader(new InputStreamReader(this.getiS()));
        this.setbR(this.bR);
    }

    this.totalLines = countTotalLines();

    if (this.getTotalLines() > 0) {
        this.fileToHash();
        this.splitFileIntoPages();
    }else 
        System.out.println("@MeasurementFile(): The file is empty can not create more data");
}

1 个答案:

答案 0 :(得分:0)

如果您的文件为空,它将返回null,因为该文件为空。 如果文件为空,您可以使用File.isEmpty()或BufferedReader.isEmpty()方法来计算。例如,

File f= new File("Foo.txt");
if (f.isEmpty){
    continue;
}
BufferedReader reader = new BufferedReader(new FileReader(f));
String line = reader.readLine();

我认为你应该做的也许是检查reader.readLine()。length< 0.例如:

String line = reader.readLine();
if(line.length < 0){
    // File is empty
    continue;
}else{
    // File is not empty
}

这将确保您的文件在您编写时包含某些内容。