簡體   English   中英

Java:從文本文件中檢索和刪除隨機行

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

我需要從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:在Main.main的TransmitToFile.returnAndDeleteRandomLine(TransmitToFile.java:247)的java.util.Random.nextInt(未知來源)中,bound必須為正( Main.java:98)

我甚至無法刪除該行,因為我仍然無法檢索該行。

你忘記了,所以將變量maxLines的值設置為文件中行的nuber,因為它為0,你會得到一個異常。

您可以添加新方法來獲取這樣的行號(如下面的答案所示: 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變量將等於文件中的行數。

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

問題是這條線

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

maxLines0的情況下,您將調用rand.nextInt(-1) 因此該參數必須為正的錯誤。

錯誤在這一行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM