Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java In and Out

I am newbie to Java. I have this exercice from school to create a BasicIO class and Main class to read and write to a file .

However my code only reads the first sentence and prints it in an infinite loop.

BasicIO.java

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class BasicIO 
{

    BasicIO()
    {
        line = null;
    }

    public void readplzthx(String filename) throws IOException
    {
        FileReader f = null;
        BufferedReader rd = null;

        f = new FileReader(filename);
        rd = new BufferedReader(f);

        line = rd.readLine();   
        rd.close();
        f.close();
    }

    public void writeplzthx(String filename)
    {

    }
    //String fn;
    String line;
}

Main.java:

import java.io.File;
import java.io.IOException;

public class Main {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException
    {
        File f = new File("test.txt");
        BasicIO io = new BasicIO();
        //io.readplzthx(f.getAbsolutePath());
        //File f = new File(args[1]);
        io.readplzthx(f.getAbsolutePath());
        do
        {
        //  io.readplzthx(f.getAbsolutePath());
            System.out.println(io.line);
        } while (io.line != null);
    }   

}
like image 270
Dung Avatar asked May 30 '26 22:05

Dung


1 Answers

    do
    {
    //  io.readplzthx(f.getAbsolutePath());
        System.out.println(io.line);
    } while (io.line != null);

That's your infinite loop. io.line doesn't change inside the loop.

Even when that's fixed, though, you'll still have the same problem. You only want to open the file once, then read from it repeatedly.

like image 60
nmichaels Avatar answered Jun 01 '26 11:06

nmichaels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!