gpt4 book ai didi

java - 我想在JAVA中读到文件的倒数第二行

转载 作者:行者123 更新时间:2023-12-01 17:47:13 24 4
gpt4 key购买 nike

每次用户登录时。我都会阅读到文件的倒数第二行 The file structure looks like (for reference) .我想知道我需要对代码进行哪些更改,以便我只能读取文件的倒数第二行。

public static boolean User(String usid) {

try {
String acc = usid;
File file = new File("C:\\Temp\\logs\\bank.log");
Scanner myReader = new Scanner(file);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
String[] substrings = data.split("[:]");
if (substrings[5].contains(acc) && substrings[4].contains("Login Successful for user")) {
a = true;
} else {
a = false;
}

}
} catch (Exception e) {
e.printStackTrace();
}

任何人都可以指导我需要对上述代码进行哪些更改才能阅读到文件的倒数第二行[注意:-此内容一旦用户登录或注销,文件就会不断添加。]

最佳答案

试试这个,你可以根据你的要求修改

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Test{



public static boolean User(String usid) {
boolean a=false;
String fileName = "c://lines.txt";
List<String> list = new ArrayList<>();
String acc = usid;
try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) {

//br returns as stream and convert it into a List
list = br.lines().collect(Collectors.toList());

for(int i=0; i<list.size()-1; i++){
String data = list.get(i);
String[] substrings = data.split("[:]");
if (substrings[5].contains(acc) && substrings[4].contains("Login Successful for user")) {
a = true;
} else {
a = false;
}
}

} catch (IOException e) {
e.printStackTrace();
}
return a;
}
}

关于java - 我想在JAVA中读到文件的倒数第二行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60847958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com