пытается прочитать текстовый файл и преобразовать их в объект с другим примитивом - PullRequest
0 голосов
/ 13 марта 2019

Я пытаюсь написать метод, который читает данные об ученике из простого текстового файла (идентификатор студента - имя студента - фамилия студента) с использованием устройства чтения и создает и возвращает соответствующий новый объект студента. , TXT-файл содержит подробности построчно ex. идентификатор студента находится в строке, а имя будет в следующей строке.

Я пытаюсь сделать это в методе readStudent ()

class StudentInputStream{

BufferedReader in;
public StudentInputStream(InputStream input) {
        in = new BufferedReader(new InputStreamReader(input));
    }

@Override
    public void close() throws IOException {
        in.close();
    }

    public Student readStudent() throws IOException {
        /*Student student1 = new student();*/
        return null; 
    }
}

1 Ответ

1 голос
/ 13 марта 2019

Код не требует пояснений, если у вас есть какие-либо вопросы, пожалуйста, скажите мне.

File file = new File("Your file's path");
     Scanner sc=null;
     try {
        sc = new Scanner(file);
     } catch (FileNotFoundException e) {
        e.printStackTrace();
     }
     ArrayList<Student> list = new ArrayList<>();
     while(sc.hasNextLine()){
         if(sc.nextLine().equalsIgnoreCase("student")){
             //Assuming each property is in the seperate line of file
         String id,name,surname=null;
         if(sc.hasNextLine()){
         id = sc.nextLine();
         /*if id is int use
          * int id = Integer.parseInt(sc.nextLine());
          */
         }
         if(sc.hasNextLine()){
             name = sc.nextLine();
         }
         if(sc.hasNextLine()){
             surname = sc.nextLine();
         }
         list.add(new Student(id,name,surname));

         }
     }

Использование bufferedReader:

InputStream in = new FileInputStream("Your file's path");
     BufferedReader br = new BufferedReader(new InputStreamReader(in));
     String str;
     ArrayList<Student> list = new ArrayList<>();
     while((str=br.readLine())!=null){
         if(str.equalsIgnoreCase("student")){
             String id=null,name=null,surname=null;
             if((str=br.readLine())!=null){
             id = str;
             /*if id is int use
              * int id = Integer.parseInt(sc.nextLine());
              */
             }
             if((str=br.readLine())!=null){
                 name = str;
             }
             if((str=br.readLine())!=null){
                 surname = str;
             }
             list.add(new Student(id,name,surname));
         }
     }

С ObjectInputStream

OutputStream out = new FileOutputStream("yourfilepath.bin");
     ObjectOutputStream outputStream = new ObjectOutputStream(out);

     Student s1 = new Student("100383", "JOHN", "MITCHELL");
     Student s2 = new Student("100346", "AMY", "CHING");


     outputStream.writeObject(s1);
     outputStream.writeObject(s2);
     outputStream.writeObject(null);//to realize that you reach the end of file

     outputStream.close();
     out.close();

     InputStream in = new FileInputStream("yourfilepath.bin");
     ObjectInputStream inputStream = new ObjectInputStream(in);

     Student temp = null;

     while((temp =(Student)inputStream.readObject())!=null){
         System.out.println(temp.id+","+temp.name+","+temp.surname);
     }

ВЫХОД

100383, ДЖОН, МИТЧЕЛЛ

100346, ЭМИ, ЧИНГ

...