微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

读取、合并和保存数据的 Java 程序

如何解决读取、合并和保存数据的 Java 程序

我对 Java 非常陌生,如果您对我正在尝试解决主题提供帮助,我将不胜感激。我想编写一个小的 Java 程序,它可以:

  1. 读取数据(表格)
  2. union 按行
  3. 将它们显示在框架中
  4. 下载文件

我到了不确定我写的代码是否真的有成效的地步,我被困在显示数据上。 我准备了两个数据文件的小例子:

汽车

Row Description Type Example
1 Name String XX
2 Year int 2021
3 Value double 0.37
4 Area double 2.84
5 Weight double 1000
6 Tyre String 210/10 R1

电机

Row Description Type Example
1 A String XY
2 B double 230
3 C int 1000
4 D int 3400
5 E int 1000

你可以找到我的Java代码,目前可以打开对话框,选择带有JFileChooser文件显示路径和读取数据(1)。我被困在显示两个表的 union 并下载文件。感谢您的帮助!

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import javax.swing.*;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;


@SuppressWarnings("serial")
public class JFileChooserExample extends JPanel {
    // use a list model and JList that works *directly* with Files
    private DefaultListModel<File> fileListModel = new DefaultListModel<>();
    private JList<File> fileJList = new JList<>(fileListModel);
    List<String>  kfz_list = new ArrayList<>();
    List<String>  motor_list = new ArrayList<>();
    static Path filePath;
    static Path filePath2;
    static Path car;
    static Path motor;

    public JFileChooserExample() {
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(new JButton(new SelectFilesAction("Select Files",KeyEvent.VK_S)));

        // help set the width and height of the JList
        fileJList.setVisibleRowCount(10);
        fileJList.setPrototypeCellValue(new File("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
        JScrollPane scrollPane = new JScrollPane(fileJList);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        setBorder(BorderFactory.createEmptyBorder(3,3,3));
        setLayout(new BorderLayout(3,3));
        add(buttonPanel,BorderLayout.PAGE_START);
        add(scrollPane,BorderLayout.CENTER);
    }
    private class SelectFilesAction extends AbstractAction {
        public SelectFilesAction(String name,int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY,mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            fc.setMultiSelectionEnabled(true);
            fc.setCurrentDirectory(new File(System.getProperty("user.home")));
            int result = fc.showOpenDialog(JFileChooserExample.this);
            if(result == JFileChooser.APPROVE_OPTION) {
                fileListModel.clear();  // clear the model of prior files
                 File[] files = fc.getSelectedFiles();
                 for (File file : files) {
                     // add all files to the model
                     boolean matches = Pattern.matches(".*car*.",file.getPath());
                     boolean matches2 = Pattern.matches(".*motor*.",file.getPath());
                     if(matches) {
                         car = file.toPath();
                     }
                     if(matches2) {
                         motor = file.toPath();
                     }
                     System.out.println("car path");
                     System.out.println(car);
                     System.out.println("motor path");
                     System.out.println(motor);

                     Charset charset = StandardCharsets.UTF_8;

                     // car read ans instantiate

                     try (BufferedReader bufferedReader = Files.newBufferedReader(car,charset)) {
                         String line;
                         while ((line = bufferedReader.readLine()) != null) {
                             // System.out.println(line);
                             kfz_list.add(line);
                         }
                     } catch (IOException ex) {
                             System.out.format("I/O error: %s%n",ex);
                         }

                     Kfz kfz1 = new Kfz();
                     //kfz1.Kfz("A",2015,23.5,2.3,"B",12.0);
                     kfz1.Kfz(kfz_list.get(0),Integer.parseInt(kfz_list.get(1)),Double.parseDouble(kfz_list.get(2)),Double.parseDouble(kfz_list.get(3)),Double.parseDouble(kfz_list.get(4)),kfz_list.get(5));

                     System.out.println("checking kfz1");
                     System.out.println(kfz1.getName() + " " + kfz1.getBaujahr());

                     // motor read and instantiate
                     try (BufferedReader bufferedReader2 = Files.newBufferedReader(motor,charset)) {
                         String line2;
                         while ((line2 = bufferedReader2.readLine()) != null) {
                             // System.out.println(line2);
                             motor_list.add(line2);
                         }
                     } catch (IOException ex) {
                             System.out.format("I/O error: %s%n",ex);
                         }

                     Motor motor1 = new Motor();
                     motor1.Motor(motor_list.get(0),Double.parseDouble(motor_list.get(1)),Integer.parseInt(motor_list.get(2)),Integer.parseInt(motor_list.get(3)),Integer.parseInt(motor_list.get(4)));
                     System.out.println("checking motor1");
                     System.out.println("Bezeichnung: " + motor1.getBezeichnung() + " " + "Max_drehmoment: " + motor1.getMax_drehmoment());
                         // end
                     fileListModel.addElement(file);

                }
            }
        }
    }

    private static void createAndShowGui() {
            JFileChooserExample mainPanel = new JFileChooserExample();

            JFrame frame = new JFrame("JFileChooser Example");
            frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(mainPanel);
            frame.pack();
            frame.setLocationRelativeto(null);
            frame.setVisible(true);
        }

        public static void main(String[] args) {
            SwingUtilities.invokelater(() -> createAndShowGui());
        }
    }

解决方法

在使用 GUI 程序时,我建议遵循 MVC 范式,其中所有 GUI 组件都位于 Gui 类中。控制器类接收 GUI 调用并将它们保存在模型中并从模型更新 GUI 调用。

为了方便使用 NetBeans IDE,您已经集成了可视化 GUI 构建器

我有意省略了源代码示例,因为如您所见,您将需要一些示例,来自以下主题:

图形界面 该类继承自 javax.swing.JFrame

控制器 将实现所有的侦听器,如 ActionListener、MouseListener、KeyListener,并将初始化所有模型。将从 GUI 同步到模型

模型 模型之一是 TableModel 要创建自定义 TableModel,只需从 AbstractTableModel 扩展您的类,并使用二维数组覆盖方法来存储表数据。

下载文件 要将数据从模型下载到文件,您需要创建一个 Java 对象并实现一个 Serializable 接口

另存为 Java

try {
        FileOutputStream fout = new FileOutputStream(file);
        ObjectOutputStream out = new ObjectOutputStream(fout);

        out.writeObject(cars);
        out.close();
    } catch (IOException ex) {
        Logger.getLogger(CarCatalog.class.getName()).log(Level.SEVERE,null,ex);
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?