Answer the question
In order to leave comments, you need to log in
Where do the empty characters come from at the beginning when writing to a file?
Why, when writing to a file, invisible characters appear at the beginning that affect the output of the result? How to solve this problem?
After executing the code, the file will have the following line: "
After reading the data from the file, the result will be: Person(, 1835012), and should be Person(Alex, 28)
import java.io.*;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person(" + name + ", " + age + ")";
}
}
interface EntityInput {
public Person readPerson() throws IOException;
}
interface EntityOutput {
public void writePerson(Person person) throws IOException;
}
class EntityOutputStream implements EntityOutput {
private final DataOutput out;
EntityOutputStream(OutputStream out) {
this.out = new DataOutputStream(out);
}
@Override
public void writePerson(Person person) throws IOException {
out.writeInt(person.getAge()); // запись возраста
if (person.getName() == null) {
out.writeUTF("defaultName");
} else {
out.writeUTF(person.getName()); // запись имени
}
}
}
class EntityInputStream implements EntityInput {
private final DataInput src;
EntityInputStream(InputStream src) {
this.src = new DataInputStream(src);
}
@Override
public Person readPerson() throws IOException {
return new Person(src.readUTF(), src.readInt()); // Создание объекта Person c считанными данными
}
}
public class App {
public static void main(String[] args) throws IOException {
Person person = new Person("Alex", 28);
EntityOutputStream out = new EntityOutputStream(new FileOutputStream("c://file.txt"));
EntityInput in = new EntityInputStream(new FileInputStream("c://file.txt"));
out.writePerson(person); // Запись в файл данных о person
System.out.println(in.readPerson()); // Считывание данных о person из файла
}
}
Answer the question
In order to leave comments, you need to log in
The characters at the beginning are non-printable characters derived from the int you write first. It reads incorrectly because you read in the wrong order. At first it is necessary to read int, then a line.
Well, just writing to a file without any structure is not correct. Read about xml, json. About bd. About serialization, in the end.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question