gpt4 book ai didi

java - 负责从 Web txt 获取数据的代码行的正确名称是什么?

转载 作者:行者123 更新时间:2023-12-02 09:58:10 25 4
gpt4 key购买 nike

我需要帮助来划分这些代码行并将它们放入方法中:

   url = new URL(URL_SOURCE);
con = url.openConnection();
is = con.getInputStream();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("pozycja");

我把它分成:

 public URLConnection openConnectionOfGivenURL(String givenURL) throws IOException {
URL url = new URL(givenURL);
return url.openConnection();
}

我不知道剩下的该怎么办。我应该用 getDOM 命名它吗?

最佳答案

我认为除了第一行和最后一行之外的所有内容都应该在一个方法中。不要尝试将代码划分得更远。例如。 Document getXml(URL url) 或者如果您只想将其与 HTTP(S) url 一起使用,则可以将其命名为 downloadXml

不进一步划分的主要原因是您应该使用 try-with-resources。

此外,您不需要标准化已解析的 DOM,因为 the parser is already creating a normalized DOM tree .

Document getXml(URL url) {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
URLConnection con = url.openConnection();
try (InputStream is = con.getInputStream()) {
return dBuilder.parse(is);
}
}

然后你像这样使用它:

URL url = new URL(URL_SOURCE);
Document doc = getXml(url);
NodeList nList = doc.getElementsByTagName("pozycja");

关于java - 负责从 Web txt 获取数据的代码行的正确名称是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55839210/

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