[英]BufferedReader is initialised but readLine returns null?
我有一個measurementFile
類,其構造函數發布在下面。 在具有main
方法的File_IO_03
類中,我實例化了上述類的對象,但是當我嘗試使用mf.getbR.readLine
readLine
控制台顯示為空。
注意: 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");
}
如果文件為空,則將返回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
}
這樣可以確保文件在寫入時包含某些內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.