有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

文本文件如何在java中读取文本文件?

我目前正在从事java项目,我想不出这个问题的解决方案。我有一个名为Student的类,它的构造函数有参数。这是代码public Student(int id, String name, String lastname, String password, int rocnik, String degree, String group, ArrayList<String> predmety)。我有一个看起来像这样的文本文件
560269 Marek Magula 23Ta3 1 bc 5ZYS11 Matematika,Informatika,Algebra; 558254 Michael Holy tarhona 1 bc 5ZYS12 Algebra,Anglictina,Informatika;这是一个包含学生信息的文本文件。它将有更多的行,但我仅显示了2行以进行说明。在另一个名为GUI的类中,我创建了一个方法

public boolean authentificate() {
   
    
return false;
}

对于start,我需要读取文本文件并为每行创建Student实例。如果我把这些数据从文本文件放到excel表格中,不是更容易做到吗


共 (2) 个答案

  1. # 1 楼答案

    以下是您在fie中的阅读方式:

    Path path = Paths.get("C:\Users ... (your path) file.txt");
    try(BufferedReader reader = Files.newBufferedReader(path)){
        int character;
        while((character = reader.read()) != -1){
            System.out.println((char) character);
        }
    }catch(IOException e){
        e.printStackTrace();
    }
    

    通过使用try-with-resources,您不必关闭阅读器,因为它是自己完成的

  2. # 2 楼答案

    您想要的是使用BufferedReader实例读取文件,并解析从中获得的每一行

    例如:

            try {
                BufferedReader reader = new BufferedReader(new FileReader("filename"));
                String line;
                while ((line = reader.readLine()) != null) {
                    // parse your line here.
                }
    
                reader.close(); // don't forget to close the buffered reader
    
            } catch (IOException e) {
                // exception handling here
            }
    

    是的,评论中给出的link提供了更全面的答案