gpt4 book ai didi

java - 连接两个 .csv 文件

转载 作者:行者123 更新时间:2023-12-01 08:51:50 25 4
gpt4 key购买 nike

我想按如下所示的方式合并两个 CSV 文件。这些文件始终具有相同的结构(例如,购物车中始终有三种产品)。

“数据库”:

ProductId, Name, Price
123, "My Product 1", 99
223, "My Product 2", 42
323. "My Product 3", 19

“购物车”:

 CustomerId, Product1, Product2, Product3
111, 123, 223, 323
112, 223, 223, 123

想要的输出:

CustomerId, Product1, Product1Name, Product1Price, Product2, Product2Name, Product2Price, Product3, Product3Name, Product3Price
111, 123, "My Product1", 99, 223, "My Product 2", 42, 323, "My Product 3", 19
112, 223, "My Product2", 41, 223, "My Product 2", 42, 123, "My Product 1", 99

我考虑使用 CSV 库通过一个小型 Java 程序来解决这个问题,而不是手动处理文件。但我想知道是否有更好的方法来做到这一点。

最佳答案

如果您想在中间步骤中不使用数据库来处理 CSV 文件(在这种情况下这无论如何都是更好的解决方案),您可以使用 CSV file JDBC driver .

下面找到一个片段来展示其原理。 (注意:除了准备代码片段所需的之外,没有进行任何进一步的调查。)

假设以下目录和文件

bin/
csv.directory/database.csv
csv.directory/shopping_cart.csv
lib/csvjdbc-1.0-31.jar
src/sub/optimal/Main.java

数据库.csv

ProductId, Name, Price
123,"My Product 1",99
223,"My Product 2",42
323,"My Product 3",19

shopping_cart.csv

111,123,223,323
112,223,223,123

Main.java

import java.sql.*;
import org.relique.jdbc.csv.CsvDriver;

public class Main {

public static void main(String[] args) throws SQLException {
String csvDirectory = "csv.directory";
String connURL = "jdbc:relique:csv:";
Connection conn = DriverManager.getConnection(connURL + csvDirectory);
try (Statement stmt = conn.createStatement()) {
String sql;
sql = "SELECT c.CustomerId,"
+ " c.Product1,"
+ " (SELECT name"
+ " FROM database AS d"
+ " WHERE d.ProductId = c.Product1"
+ " ) AS Product1Name,"
+ " (SELECT price"
+ " FROM database AS d"
+ " WHERE d.ProductId = c.Product1"
+ " ) AS Product1Price"
+ " FROM shopping_cart AS c";
ResultSet results = stmt.executeQuery(sql);

boolean append = true;
CsvDriver.writeToCsv(results, System.out, append);
}
}
}

编译

javac -d bin/ -cp lib/* src/sub/optimal/Main.java

运行

java -cp bin:lib/* sub.optimal.Main

输出

CustomerId,Product1,PRODUCT1NAME,PRODUCT1PRICE
111,123,My Product 1,99
112,223,My Product 2,42

关于java - 连接两个 .csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42342244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com