public void loadFromFile() {
System.out.println("Loading books...");
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream("books.txt");
Scanner sc = new Scanner(fileInput);
if (sc.hasNext()) {
System.out.format("%-5s %-45s %-10s", "Id", "Name", "Price");
System.out.println();
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} else {
System.out.println("(empty)");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.err.println("File not found");
} finally {
try {
fileInput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// TODO: your code here
}
我有一個 .txt 檔案,要求程式讀取它并將其決議為物件。每行是一個物件,包括屬性 id、名稱和價格
如何將文本決議為物件
uj5u.com熱心網友回復:
public static final class Book {
private int id;
private String name;
private double price;
}
public static void main(String... args) throws FileNotFoundException {
List<Book> books = readMovies(new File("a.txt"));
}
private static List<Book> readMovies(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
scan.useLocale(Locale.ENGLISH);
List<Book> books = new ArrayList<>();
while (scan.hasNext()) {
Book book = new Book();
book.id = scan.nextInt();
String line = scan.nextLine().trim();
int pos = line.indexOf(" ");
book.name = line.substring(0, pos).trim();
book.price = Double.parseDouble(line.substring(pos 1).trim());
books.add(book);
}
return books;
}
}
uj5u.com熱心網友回復:
// 這段代碼可以幫到你,樂于助人
匯入 java.io.*; 公共類 FileTextCheck {
public static void main(String[] args) {
User u1 = new User("Sudhakar", 27, "Male");
User u2 = new User("Richa", 25, "Female");
try {
FileOutputStream fos = new FileOutputStream(new File("/home/orange/Desktop/myfile.txt"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(u1);
oos.writeObject(u2);
oos.close();
fos.close();
FileInputStream fis = new FileInputStream(new File("/home/orange/Desktop/myfile.txt"));
ObjectInputStream ois = new ObjectInputStream(fis);
User pr1 = (User) ois.readObject();
User pr2 = (User) ois.readObject();
System.out.println(pr1.toString());
System.out.println(pr2.toString());
ois.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
private String gender;
User(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
@Override
public String toString() {
return "Name:" name "\nAge: " age "\nGender: " gender;
}
}
}
uj5u.com熱心網友回復:
您不能將任何型別的文本決議為 java 物件。文本應為 JSON 格式。您可以使用Gson庫將JSON 字串決議為 java 物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374433.html
