-6

I'm currently working on java project and I can't think solution for this problem. I have class called Student and its constructor has paramaters. Here's the code public Student(int id, String name, String lastname, String password, int rocnik, String degree, String group, ArrayList<String> predmety). I have text file that looks just like this
560269 Marek Magula 23Ta3 1 bc 5ZYS11 Matematika,Informatika,Algebra; 558254 Michael Holy tarhona 1 bc 5ZYS12 Algebra,Anglictina,Informatika; It's textfile with student information. It will have more rows but I showed just 2 for illustration.In my other class called GUI I created method

public boolean authentificate() {
   
    
return false;
}

For start I need to read the text file and create instance of Student for each row. Also wouldn't it be easier to do if I put those data from textfile to excel table?

marek
  • 15
  • 7
  • 3
    Does this answer your question? [Reading a plain text file in Java](https://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java) – OH GOD SPIDERS Nov 29 '21 at 10:51
  • Not really. I can't seem to understand how to assign data from textfile that are separated by whitespace.Because I need to asssign first as int, after whitespace there is string, and at the end there are data separated by , that need to be asssigned to arraylist – marek Nov 29 '21 at 10:56
  • @marek read each line into a `String`, then use the `split` method to split on every comma, which seperates the values. Then treat each one as you need it – f1sh Nov 29 '21 at 10:58
  • I didn't do research on working with excel files. It was just a thought that popped in my head. – marek Nov 29 '21 at 10:58
  • Okay I'll try that. Thank you @f1sh – marek Nov 29 '21 at 10:58

2 Answers2

1

What you want is to use a BufferedReader instance to read from the file, and parse each line that you get from it.

For example:

        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
        }

And yes, the link given in the comments provide much more comprehensive answers.

Mubin
  • 130
  • 1
  • 9
0

This is how you'll read from the 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();
}

By using try-with-resources you won't have to close the reader since it does it by itself.

Fanis G
  • 66
  • 1
  • 7