在读取/写入文件时使用分隔符

时间:2013-05-17 12:27:34

标签: java file-io

我正在尝试使用此方法从java中的文件读取写入,我已经过度使用Externalizable的方法我如何使用但是某种分隔符如“;” at string,用于了解带空格的字符串有多长。

    public class Person extends Om {

        private String job;
        private ArrayList<Integer> hobbiesIDs;
        private String birthDate;

    @Override
    public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
        this.setId(Integer.parseInt(in.readUTF()));
        this.setFirstNname(in.readUTF());
        this.setLastName(in.readUTF());
        this.setBirthDate(in.readUTF());
        this.setJob(in.readUTF());

    }
    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(Integer.toString(this.getId()));
        out.writeUTF(this.getFirstNname());
        out.writeUTF(this.getLastName());
        out.writeUTF(this.getBirthDate());
        out.writeUTF(this.getJob());
    }
    }

    @SuppressWarnings("unchecked")
    public void readFile() {
            ArrayList<Person
> tempPersons = new ArrayList<>()

        try {
            InputStream inputStream = new FileInputStream("Persoane.txt");
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);

            tempPersons = (ArrayList<Person>) objectInputStream.readObject();
            persons = (ArrayList<Person>) tempPersons.clone();

            objectInputStream.close();
            inputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("exception: " + e);
        }

    public void writeFile() {
        try {
            OutputStream outputStream = new FileOutputStream("Persoane.txt");
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);

            objectOutputStream.writeObject(persons);
            objectOutputStream.flush();
            outputStream.flush();

            objectOutputStream.close();
            outputStream.close();

        } catch (IOException e) {
            System.out.println("exception: " + e);
        }

0 个答案:

没有答案