在此
Document document = documentBuilder.parse(filename);
我试图通过buffered input stream
读取一组Xml文件。当我在命令提示符下输入文件时,我收到错误As System Cannot find the specified File
。有人可以建议如何从这里继续
import java.io.File;
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XMLFile {
public static void main(String argv[]) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory
.newDocumentBuilder();
BufferedReader bufferRead = new BufferedReader(
new InputStreamReader(System.in));
String s = bufferRead.readLine();
File dir = new File(s);
String[] children = dir.list();
if (children == null) {
} else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
Document document = documentBuilder.parse(filename);
System.out.println(filename);
NodeList employees = document
.getElementsByTagName("connection");
for (int q = 0; q < employees.getLength(); q++) {
System.out.println(employees.getLength());
Node employee = employees.item(q);
NamedNodeMap attribute = employee.getAttributes();
Node nodeAttr = attribute.getNamedItem("server");
nodeAttr.setTextContent("aventador.am.lilly.com:1530");
Node nodeAttr1 = attribute.getNamedItem("service");
Node nodeAttr2 = attribute.getNamedItem("port");
nodeAttr1.setTextContent("tst806");
nodeAttr2.setTextContent("");
}
System.out.println(filename);
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory
.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(
filename));
transformer.transform(domSource, streamResult);
System.out.println("The XML File was ");
}
}
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
} catch (Exception sae1) {
sae1.printStackTrace();
}
}
}
答案 0 :(得分:1)
在您的其他区域内,您正尝试Document document = documentBuilder.parse(filename);
filename参数应该是URI - 意思是完整的文件路径。但是您只传递文件名,因此无论您的输入目录如何,DocumentBuilder都会查看XML文件的当前目录。更改以下行
String filename = children[i];
到
String filename = dir.getAbsolutePath() + File.separator + children[i];
这应解决问题。