簡體   English   中英

我想讀到 JAVA 文件的倒數第二行

[英]I want to read till the second last line of the file in JAVA

每次用戶登錄時,我都在閱讀文件第二行文件結構如下(供參考) .我想知道我需要對代碼進行哪些更改,以便我只能讀取文件的倒數第二行。

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

這已經在鏈接中得到了回答

暫無
暫無

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

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