如何从文本转换为java

问题描述 投票:0回答:4
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,名称和价格

我怎么可以将文本解析为对象

java file object oop parsing
4个回答
0
投票
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;
    }
}

0
投票

//此代码可以帮助您,乐于帮助您

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


0
投票
GSON

库将JSON字符串解析为Java对象。

import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.GridPane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import java.io.*; import java.net.*; import java.util.Scanner; public class ChessGame extends Application { private static final int SIZE = 8; private static final int TILE_SIZE = 80; private static boolean isMultiplayer = false; private static boolean isAI = false; private static Socket socket; private static BufferedReader input; private static PrintWriter output; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Select Mode: \n1. Play Online \n2. Play vs AI \n3. Play Locally"); int choice = scanner.nextInt(); if (choice == 1) { isMultiplayer = true; System.out.println("Are you Host? (yes/no)"); String role = scanner.next(); if (role.equalsIgnoreCase("yes")) { new Thread(ChessGame::startServer).start(); } else { new Thread(ChessGame::startClient).start(); } } else if (choice == 2) { isAI = true; } launch(args); } @Override public void start(Stage primaryStage) { GridPane grid = new GridPane(); for (int row = 0; row < SIZE; row++) { for (int col = 0; col < SIZE; col++) { Rectangle tile = new Rectangle(TILE_SIZE, TILE_SIZE); tile.setFill((row + col) % 2 == 0 ? Color.BEIGE : Color.BROWN); grid.add(tile, col, row); } } Scene scene = new Scene(grid, SIZE * TILE_SIZE, SIZE * TILE_SIZE); primaryStage.setTitle("Chess Game"); primaryStage.setScene(scene); primaryStage.show(); } // 1️⃣ Multiplayer Server private static void startServer() { try (ServerSocket serverSocket = new ServerSocket(5000)) { System.out.println("Waiting for player..."); socket = serverSocket.accept(); System.out.println("Player connected!"); setupConnection(socket); } catch (IOException e) { e.printStackTrace(); } } // 2️⃣ Multiplayer Client private static void startClient() { try { socket = new Socket("localhost", 5000); System.out.println("Connected to server!"); setupConnection(socket); } catch (IOException e) { e.printStackTrace(); } } // 3️⃣ Handling Multiplayer Moves private static void setupConnection(Socket socket) { try { input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new PrintWriter(socket.getOutputStream(), true); new Thread(() -> { try { while (true) { String opponentMove = input.readLine(); if (opponentMove != null) { System.out.println("Opponent moved: " + opponentMove); } } } catch (IOException e) { e.printStackTrace(); } }).start(); Scanner scanner = new Scanner(System.in); while (true) { System.out.print("Enter move (e.g., e2 e4): "); String move = scanner.nextLine(); output.println(move); } } catch (IOException e) { e.printStackTrace(); } } // 4️⃣ AI Opponent (Minimax Placeholder) private static String getAIMove() { return "e7 e5"; // Replace with Minimax logic } }

0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.