3

So I'm a beginner at programming and I'm trying to figure out what the problem is with the

following functions. The problem is with the scan.hasNext() method I have two println

statements (one right after I make scan, and one on the second method) telling me whether scan.hasNext() returns true or false. The weird thing is

that the code as it is now enters the while loop which is what should happen, but when I

delete one of the println statements it doesn't go in the loop and the other print

statement tells me scan.hasNext() is false.

This is weird because I change nothing except for erasing a print statement. Furthermore I

found if I add one more for a total of 3 print statements it will be false again, and if I

add a fourth it's true again, etc. I think I just don't understand how hasNext works since I

have no idea how to follow where the "cursor" should be.

public void createFile(String filename){    
    final File file = new File(filename);       
    try{
        scan = new Scanner(file);
        **System.out.println(scan.hasNext());**
        buff = new BufferedWriter(new FileWriter(filename), 1);         
    }
    catch(Exception e1){
        try{
            buff = new BufferedWriter(new FileWriter(filename));
            scan = new Scanner(file);
        }
        catch(Exception e2){
            System.out.println("Error trying to create file");
        }   
    }
}

public String readFile(){
    String fileContents = "";
    **System.out.println(scan.hasNext());**
    if(scan.hasNext())
        while(scan.hasNext())
            fileContents = fileContents + scan.next()+" "+scan.next()+" "+scan.next();
    return fileContents;

}
Luis Cruz
  • 29
  • 3

1 Answers1

0

Okay so I figured it out. vishal_aim's suggestion helped me figure it out. The following line

buff = new BufferedWriter(new FileWriter(filename), 1);

was truncating my file back to zero size. the reason being is because I really meant to do this.

buff = new BufferedWriter(new FileWriter(filename, true));

Firstly I put one because I thought java automatically made 1 true when it asked for a boolean. Secondly I was trying to use a constructor of the FileWriter class that lets me append to the end of a file. If you don't include the true with your filename it will make a new file truncating anything in the file you have to 0. This was just a tired mistake I had forgotten if I needed to put the boolean on BufferedWriter or FileWriter. Also in case you're wondering the reason the BufferedWriter constructor wasn't giving me and error is because there is a constructor for it that takes an int, the int being the buffer size. Thank you all for your contribution.

Luis Cruz
  • 29
  • 3