簡體   English   中英

從文件中讀取最后一行

[英]Read last line from a file

因此,我試圖讀取Java中的文件。 除非最后一行為空,否則它可以正常工作,在這種情況下,它將被忽略; 但我也需要閱讀此空行。

這是我的代碼:

try
        {
            BufferedReader in = new BufferedReader(new     FileReader("filename.txt"));

        String Line;

        while((Line = in.readLine()) != null)
        {
            System.out.println("L| " + Line);
        }

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

首先使用掃描儀類...因為它們使用起來更容易嗡嗡聲....然后將每行存儲在列表中,然后獲取最后一行..以下是代碼:

public void readLast()throws IOException{
        FileReader file=new FileReader("E:\\Testing.txt");  //address of the file 
        List<String> Lines=new ArrayList<>();  //to store all lines
        Scanner sc=new Scanner(file);
        while(sc.hasNextLine()){  //checking for the presence of next Line
            Lines.add(sc.nextLine());  //reading and storing all lines
        }
        sc.close();  //close the scanner
        System.out.print(Lines.get(Lines.size()-1)); //displaying last one..
    }

暫無
暫無

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

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