0

所以我正在尝试用 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();}
    }
4

1 回答 1

1

首先使用扫描仪类......因为它们更容易使用......然后将每一行存储在一个列表中,然后获取最后一行..这是代码:

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..
    }
于 2014-05-14T06:21:29.340 回答