0

这是一个简单的示例,用于将 xml 文件读入 WebRowSet 对象,然后将数据从该对象加载到数据库。

import javax.sql.rowset.RowSetProvider;
import javax.sql.rowset.WebRowSet;
import javax.sql.rowset.spi.SyncProviderException;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;


public class WebRowSetTest {
    public static void main(String[] args) throws SQLException {

        // Create WebRowSet object and populate it with data from xml-file.
        WebRowSet receiver = RowSetProvider.newFactory().createWebRowSet();
        Path file = Paths.get("priceList.xml");
        try (InputStream in = Files.newInputStream(file)) {
            receiver.readXml(in);
        } catch (IOException x) {
            x.printStackTrace();
        }
        System.out.println("WebRowSet deserialiazed.");

        // Establish connection with database
        String connectionURL = "jdbc:mysql://localhost:3306/testdb";
        Properties connectionProps = new Properties();

        connectionProps.put("user", "root");
        connectionProps.put("password", "1234");
        connectionProps.put("serverTimezone", "Europe/Moscow");
        Connection conn = DriverManager.getConnection(connectionURL, connectionProps);
        conn.setAutoCommit(false);

        // Load data from WebRowSet object to database.
        try {
            receiver.acceptChanges(conn);
        } catch (SyncProviderException spe) {
            System.out.println("You need specify how to resolve the conflict.");
        }

        // Close connection.
        conn.close();
    }
}

还有另一种读取 xml 文件的方法,它使用 Reader 而不是 InputStream。因此,我可以将用于将 xml 文件读入 WebRowSet 的代码行替换为以下内容:

    FileReader fReader = null;
    try {
        fReader = new FileReader("priceList.xml");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    receiver.readXml(fReader);

但这不是真的吗,使用 InputStream 将 xml 文件读入 WebRowSet 对象比使用 Reader 更快?如果是这样,那么在这种情况下 readXml(Reader reader) 的目的是什么?

4

1 回答 1

2

一个采用InputStream(面向字节),另一个采用Reader(面向字符)。提供的方法更多是为了方便。在某些情况下,您有一个InputStream, 而在另一些情况下,Reader被迫转换为特定类型很麻烦,而行集参考实现使用的底层 XML 库能够很好地处理任何一个。因此,两者都提供既便宜又方便。

我不知道你为什么认为InputStream会比读者更快。哪个更快在很大程度上取决于流或读取器的实际类型(例如缓冲与否)。由于 XML 是一种面向字符的格式,因此使用可能Reader具有较小的优势,但如果与缓冲与非缓冲相比,这将是一个明显的差异,我会感到惊讶。

所以,简而言之,这两种方法存在的原因是方便,而不是性能。

例如,如果我已经有一个带有值的字符串,那么构造 aStringReader比尝试InputStream使用 a派生 a 更方便ByteArrayInputStream

于 2019-05-22T16:34:06.620 回答