I am developing an desktop application which reads specific XML Elements using XPath and displays them in text fields in a JFrame
.
So far, the program ran smoothly until I decided to pass a String
variable in the File
class.
public void openNewFile(String filePath) {
//file path C:\\Documents and Settings\\tanzim.hasan\\my documents\\xcbl.XML
//is passed as a string from another class.
String aPath = filePath;
//Path is printed on screen before entering the try & catch.
System.out.println("File Path Before Try & Catch: "+filePath);
try {
//The following statement works if the file path is manually written.
// File xmlFile = new File ("C:\\Documents and Settings\\tanzim.hasan\\my documents\\xcbl.XML");
//The following statement prints the actual path
File xmlFile = new File(aPath);
System.out.println("file =" + xmlFile);
//From here the document does not print the expected results.
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
XPath srcPath = XPathFactory.newInstance().newXPath();
XPathShipToAddress shipToPath = new XPathShipToAddress(srcPath, doc);
XPathBuyerPartyAddress buyerPartyPath = new XPathBuyerPartyAddress(srcPath, doc);
} catch (Exception e) {
//
}
}
If I define the xmlFile
with a static path (i.e. manually write it) then the program works as expected. However, instead of writing a static path, if I pass the path as a string variable aPath
it does not print the expected results.
I have done a bit of googling but failed to find anything concrete.
Just use the builtin object methods:
System.out.println("file = "+xmlFile.toString());
You could also use:
System.out.println("f = " + f.getAbsolutePath());
Also, if you're having issues wit hthe file not existing, check first then proceed:
File file = new File (aPath);
if(file.exists()) {
//Do your work
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With