簡體   English   中英

使用緩沖讀取器在java中讀取文本文件時獲取null

[英]getting null when reading a text file in java using buffered reader

我在讀取java中的文本文件並將其分配給數組時遇到問題。 該程序正在運行,但我得到null。 我嘗試將代碼更改為最簡單的代碼,就像您在下面看到的那樣。 因為這個應該真正循環文本文件。 但我這樣做是為了讓我很容易看出問題出在哪里。 但問題是我不知道為什么它仍然輸出null。

該文件肯定在我指定的目錄中,因為當我使用以下方法檢查它時,內置方法存在返回true:

if(ofile.exists()==true){
System.out.println("exist");
}else{
System.out.println("not exist");
}

請我幫忙,確定這背后的錯誤,為什么它返回null。

public static void main(String args[]){

    String[] eq=new String[50];
    String[]ea=new String[50];
    String[]eb=new String[50];
    String[] ec=new String[50];
    String[]ed=new String[50];
    char[] ans=new char[50];
    String strtemp;
    File ofile= new File("J:\\questions.txt");
    BufferedInputStream bis= null;
    FileInputStream fis= null;
    DataInputStream dis=null;




    int ii=0;
    int score=0;



    System.out.println(eq[1] + "\n" + ea[1] + "\n" + eb[1] + "\n" + ec[1] + "\n" + ed[1] + "\n" + "\n" + "Answer: ");
    String strans=x.nextLine();
    char y=strans.charAt(0);
    if(y==ans[1]){
    score++;
    }else{

    }


    try{
    fis=new FileInputStream(ofile);
    bis=new BufferedInputStream(fis);
    dis=new DataInputStream(bis);

    while(dis.available()!=0){

    eq[1]=dis.readLine(); ea[1]=dis.readLine(); 
    eb[1]=dis.readLine(); ec[1]=dis.readLine();
    ed[1]=dis.readLine(); strtemp=dis.readLine();
    ans[1]=strtemp.charAt(0); 

    }

    bis.close();
    dis.close();
    fis.close();


    }catch(FileNotFoundException e){
    e.printStackTrace();
    }catch(IOException e){
    e.printStackTrace();

    }


    }

我想我有類似的問題。 據我所知, dis.available返回0,即使有文本要讀。 嘗試在緩沖區中讀取內容。

以下是使用BufferedReader在Java中讀取文本文件的方法:

  BufferedReader reader = null; try { reader = new BufferedReader( new FileReader( "J:\\\\questions.txt") ); String line = null; do { line = reader.readLine(); if( line != null ) { // Do Something with line } } while( line != null ); } catch (Exception e) { e.printStackTrace(); } finally { if( reader != null ) try { reader.close(); } catch (IOException e) { } } 

`available'在javadoc中描述為

int available()返回可以從此輸入流中讀取(或跳過)的字節數的估計值,而不會被下一次調用此輸入流的方法阻塞。

它最初會變為0,因為你還沒有讀過它。 不要使用available於此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM