Java: extracting and removing a random line from a text file
I need to get and remove a random line from a txt file (same line). So far I have 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. Most recent error:
MaxLines () value 0 Exception on thread "main" java.lang.IllegalArgumentException: border must be positive on java.util.Random.nextInt (Unknown source) at TransmitToFile.returnAndDeleteRandomLine (TransmitToFile.java:247) at Main.main (Main .java: 98)
I couldn't even work on deleting the line because I still can't get the line.
source to share
You forgot, so set a variable value maxLines
for the line number in the file and from the moment you get it, you will get an exception.
You can add a 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 to:
int maxLines = 0;
in
int maxLines = countLines(dir);
So the variable maxLines
will be equal to the number of lines in your file.
source to share
Random.nextInt(N)
provides 0 .. N-1
. Since all indices count from 0, but people count from 1, there was a stir.
The general code can be made simpler:
public static String returnAndDeleteRandomLine(String dir) throws IOException {
Path path = Paths.get(dir);
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
if (lines.isEmpty()) {
throw new IOException("Empty file: " + dir);
}
Random rand = new Random();
int lineIndex = rand.nextInt(lines.size()); // 0 .. lines.size() - 1
String line = lines.get(lineIndex);
System.out.printf("Line %d: %s%n", (lineIndex + 1), line);
lines.remove(lineIndex);
Files.write(path, lines, StandardCharsets.UTF_8,
StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
return line;
}
source to share
The error is on this line:
int randomNumber = rand.nextInt(maxLines - 1) + 1;
You must add a check to check the size first:
int totalLines = maxLines - 1;
if(totalLines > 0) {
Random rand = new Random ();
int randomNumber = rand.nextInt (totalLines) + 1;
System.out.println("Value of randomNumber: " + randomNumber);
} else {
return null;
}
source to share