【问题标题】:Java: Retrieve and Delete Random Line from Text FileJava:从文本文件中检索和删除随机行
【发布时间】:2023-03-25 08:26:01
【问题描述】:

我需要从 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(未知来源)在 TransmitToFile.returnAndDeleteRandomLine(TransmitToFile.java:247) 在 Main.main(Main.java:98)

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

【问题讨论】:

    标签: java io


    【解决方案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】:

      您忘记了将变量 maxLines 的值设置为文件中的行数,因为它是 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 变量将等于文件中的行数。

      【讨论】:

      • 如果文件为空(maxlines = 0),此解决方案仍然会失败,因此您还应该检查 if(maxLines = 0) return;或者其他的东西。在现实生活中可能不是什么大问题,但值得注意。
      【解决方案3】:

      错误在这一行:

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

      【讨论】:

        【解决方案4】:

        问题是线

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

        如果maxLines0,那么您调用的是rand.nextInt(-1)。因此这个参数必须为正的错误。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-11-08
          • 1970-01-01
          • 2011-12-26
          • 1970-01-01
          • 2011-08-13
          • 1970-01-01
          • 2015-02-06
          • 1970-01-01
          相关资源
          最近更新 更多