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

时间:2015-08-06 09:05:21

标签: java io

我需要从txt文件(同一行)中检索和删除随机行。到目前为止,我已经提出了以下代码:

 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();
    }


 }

但我一直有不同的错误。最近的错误是:

  

maxLines()的值0线程中的异常" main"   java.lang.IllegalArgumentException:bound必须是正数   java.util.Random.nextInt(未知来源)at   TransmitToFile.returnAndDeleteRandomLine(TransmitToFile.java:247)at   Main.main(Main.java:98)

我甚至无法删除该行,因为我仍然无法检索该行。

4 个答案:

答案 0 :(得分:1)

你忘记了,所以将变量maxLines的值设置为文件中行的nuber,因为它是0,你得到一个例外。

您可以添加新方法来获取此类行号(如此答案所示: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;
    }

并改变您的代码:

int maxLines = 0;

为:

int maxLines = countLines(dir);

这样maxLines变量将等于文件中的行数。

答案 1 :(得分:1)

Random.nextInt(N)发送0 .. N-1。由于所有指数均从0开始计算,但人数从1开始计算,因此存在混淆。

通用代码可以更简单:

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

答案 2 :(得分:0)

问题在于

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

如果maxLines0,则您正在调用rand.nextInt(-1)。因此,该参数必须为正的错误。

答案 3 :(得分:0)

错误在这一行:

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

您应首先检查尺寸:

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