【问题标题】:Fastest and best way to write huge data in XML file in Java [closed]用Java在XML文件中写入大量数据的最快和最好的方法[关闭]
【发布时间】:2021-04-12 11:55:43
【问题描述】:

我们在 Java 中使用 FileOutputStream 将数据写入 XML 文件,但这种方式需要更长的时间。任何人都可以提出一个例子,我们可以比下面的方法更好地将数据写入 XML 文件。?

/**
 * This function output data into file
 * 
 * @param result
 * @param fileName
 * @param folderName
 */
private static void writeResultToFile(String result, String fileName, String folderName, String extension) {
    try {
        if (result != null && !result.equalsIgnoreCase("")) {
            byte bWrite[] = result.getBytes();
            OutputStream os = new FileOutputStream(folderName + "/" + fileName + "." + extension);
            for (int x = 0; x < bWrite.length; x++) {
                os.write(bWrite[x]); // Writes the bytes
            }
            os.close();
        }
    } catch (Exception ex) {
        /*
         * Logging
         */
    }
}

【问题讨论】:

  • 你为什么使用result.equalsIgnoreCase("")?您认为大小写对空字符串很重要吗?显然与result.equals("") 没有区别,但您应该使用result.isEmpty() 来表达实际意图。
  • 是的,可以改进。

标签: java xml performance file-handling


【解决方案1】:

不要逐字节写入,使用以byte[] 作为参数的写入方法。详情请见https://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html#write-byte:A-

此外,由于您有一个字符串(即字符数据)以开始考虑使用Writer

【讨论】:

猜你喜欢
  • 2010-11-06
  • 2015-02-07
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
相关资源
最近更新 更多