简体   繁体   English

Java:从文本文件中检索和删除随机行

[英]Java: Retrieve and Delete Random Line from Text File

I need to retrieve and delete a random line from a txt file (the same line). 我需要从txt文件(同一行)中检索和删除随机行。 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) maxLines()的值0线程“main”中的异常java.lang.IllegalArgumentException:在Main.main的TransmitToFile.returnAndDeleteRandomLine(TransmitToFile.java:247)的java.util.Random.nextInt(未知来源)中,bound必须为正( Main.java:98)

I could not even work on deleting the line because I'm still unable to retrieve the line. 我甚至无法删除该行,因为我仍然无法检索该行。

You forgot so set the value of variable maxLines to nuber of lines in file and since its 0 you get an exception. 你忘记了,所以将变量maxLines的值设置为文件中行的nuber,因为它为0,你会得到一个异常。

You can add new method to get line numbers like this (as shown in this answer: number-of-lines-in-a-file-in-java ): 您可以添加新方法来获取这样的行号(如下面的答案所示: 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. 这样maxLines变量将等于文件中的行数。

Random.nextInt(N) delivers 0 .. N-1 . Random.nextInt(N)提供0 .. N-1 As all indices are counting from 0, but humans count from 1, there was a mix-up. 由于所有指数均从0开始计算,但人数从1开始计算,因此存在混淆。

The general code can be done 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;
}

The problem is the line 问题是这条线

int randomNumber = rand.nextInt(maxLines - 1) + 1;

In the case where maxLines is 0 , then you're calling rand.nextInt(-1) . maxLines0的情况下,您将调用rand.nextInt(-1) Hence the error that this parameter must be positive. 因此该参数必须为正的错误。

The error is in this line: 错误在这一行:

int randomNumber = rand.nextInt(maxLines - 1) + 1;

You should 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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM