我需要从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();
}
}但我总是犯不同的错误。最近的错误是:
线程“主”TransmitToFile.returnAndDeleteRandomLine(TransmitToFile.java:247)中maxLines() 0异常的值:在Main.main at Main.main(Main.java:98)的java.util.Random.nextInt(未知源)处,绑定必须为正
我甚至无法删除该行,因为我仍然无法检索该行。
发布于 2015-08-06 09:11:20
您忘记了将变量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变量将等于文件中的行数。
发布于 2015-08-06 10:03:58
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;
}发布于 2015-08-06 09:08:26
问题是这条线
int randomNumber = rand.nextInt(maxLines - 1) + 1;在maxLines为0的情况下,您将调用rand.nextInt(-1)。因此,该参数必须为正的错误。
https://stackoverflow.com/questions/31851368
复制相似问题