如何读取 java 中的文本文件?
How to read from textfile in java?
我目前正在处理 java 项目,我想不出解决这个问题的方法。我有 class 调用 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 行 illustration.In 我的另一个 class 称为 GUI 我创建了方法
public boolean authentificate() {
return false;
}
首先,我需要读取文本文件并为每一行创建 Student 实例。如果我将这些数据从文本文件放入 excel table?
也不会更容易吗?
您想要的是使用 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 提供了更全面的答案。
这就是您从 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,您不必关闭 reader,因为它会自动关闭。
我目前正在处理 java 项目,我想不出解决这个问题的方法。我有 class 调用 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 行 illustration.In 我的另一个 class 称为 GUI 我创建了方法
public boolean authentificate() {
return false;
}
首先,我需要读取文本文件并为每一行创建 Student 实例。如果我将这些数据从文本文件放入 excel table?
也不会更容易吗?您想要的是使用 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 提供了更全面的答案。
这就是您从 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,您不必关闭 reader,因为它会自动关闭。