Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Retrieve and Delete Random Line from Text File

Tags:

java

io

I need to retrieve and delete a random line from a txt file (the same line). Thus far I've come up with the following code:

 public String returnAndDeleteRandomLine(String dir) throws FileNotFoundException, IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
        //StringBuilder sb = new StringBuilder();
        //System.out.println("Value of line before while() " + line);

        ArrayList fileContents = new ArrayList();
        int maxLines = 0;


        String line = br.readLine();
        //System.out.println("Value of line before while() " + line);

        while (line != null) {
            fileContents.add(line.toString());
            line = br.readLine();
            //System.out.println("Value of line is: " + line);
        }

        System.out.println("Value of maxLines() " + maxLines);

        Random rand = new Random();
        int randomNumber = rand.nextInt(maxLines - 1) + 1;
        System.out.println("Value of randomNumber: " + randomNumber);
        int lineNumber = randomNumber;

        if (fileContents.isEmpty()) {
            return null;
        } else System.out.println("Value of random line: " + fileContents.get(randomNumber).toString());
        return fileContents.get(randomNumber).toString();
    }


 }

But I keep getting different errors. The most recent error was:

Value of maxLines() 0 Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive at java.util.Random.nextInt(Unknown Source) at TransmitToFile.returnAndDeleteRandomLine(TransmitToFile.java:247) at Main.main(Main.java:98)

I could not even work on deleting the line because I'm still unable to retrieve the line.

like image 350
Kay Mart Avatar asked Jul 22 '26 04:07

Kay Mart


1 Answers

You forgot so set the value of variable maxLines to nuber of lines in file and since its 0 you get an exception.

You can add new method to get line numbers like this (as shown in this answer: number-of-lines-in-a-file-in-java):

public int countLines(String filename) throws IOException {
        LineNumberReader reader = new LineNumberReader(new FileReader(filename));
        int cnt = 0;
        String lineRead = "";
        while ((lineRead = reader.readLine()) != null) {
        }

        cnt = reader.getLineNumber();
        reader.close();
        return cnt;
    }

And change your code from:

int maxLines = 0;

to:

int maxLines = countLines(dir);

So that the maxLines variable will be the equal to the number of lines in your file.

like image 193
Kiki Avatar answered Jul 24 '26 17:07

Kiki



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!