java - 从文件中读取最后一行

标签 java file-io

所以我正在尝试用 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..
    }

关于java - 从文件中读取最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16477388/

相关文章:

java - 获取ArrayList中值的索引

java - 使用 Active Objects ORM for Java 的经验?

python - r 和 rb 模式下解析文本文件的区别

java - Blob 数据部分插入数据库

java - 检查 TypeElement 是类还是接口(interface)

java - 如何使用 GWT RPC 在客户端保存文件?

java - isDirectory() 方法在 java 包 'false' 上调用时返回 'com'

c - C 中的魔法与 malloc、fork 和 open

java - 从同一应用程序小部件的多个实例打开 Activity 的多个实例

c# - 无法删除 arraylist 中的项目