views:

66

answers:

3

I'm having a problem reading a text file in java and assigning it to an array. The program is running but I'm getting null. I tried changing the code to its simplest for just like what you see below. Because this one should really loop through the text file. But I'm doing it this way so that I will easily see where's the problem. But the problem is that I don't know why is it still outputting null.

The file is certainly in the directory I've specified since the built in method exists returned true when I check it using this one:

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

please I need help, determining the error behind this, why is it returning 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();

    }


    }
+4  A: 

I think i had a similar problem. As far as i could tell the dis.available returns 0 even if there is text to read. Try to read something in a buffer.

kasten
+1. If you're ever using `available()` and functionally relying on what it returns, you're probably doing something wrong. Always returning `0` is a perfectly compliant implementation of `available()`.
Mark Peters
+3  A: 
Nik
+2  A: 

`available' is described in the javadoc as

int available() Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

It's initially going to be 0 because you haven't read from it yet. Don't use available for this.

Nathan Hughes