Home > Blockchain >  How to convert from text to object in Java
How to convert from text to object in Java

Time:12-04

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
}

i have a .txt file with the requirement a program reads it and parses it into object. Each line is an object including attributes id, name and price

how can I parse text to object

CodePudding user response:

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;
    }
}

CodePudding user response:

// this code can help you, happy to help

import java.io.*; public class 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;
    }
}

}

CodePudding user response:

You cannot parse any type of text to a java object. The text should be in JSON format. You can parse JSON string to java object using Gson library.

  • Related