i want to import an XML file into my Java application .
this is the function :
static void lireFichier(String fichier) throws Exception
{
SAXBuilder sxb = new SAXBuilder();
document = sxb.build(new File(fichier));
racine = document.getRootElement();
}
and this is how i call it
lireFichier("exemple.xml");
This is part of a Swing application. I want the user to be able to specify the XML file to open. How do I do this?
This is really a basic concept that could have been easily solved with minimal research.
You need to spend some time reading through Creating a GUI With JFC/Swing and How to Use File Choosers in particular.
I'd also recommend a crash course on the java.io.File API as well...
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Open stuff");
fc.addChoosableFileFilter(new FileFilter() {
#Override
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".xml") || f.isDirectory();
}
#Override
public String getDescription() {
return "XML Document (*.xml)";
}
});
switch (fc.showOpenDialog(null)) {
case JFileChooser.APPROVE_OPTION:
File file = fc.getSelectedFile();
lireFichier(file.getPath());
break;
}
- Its simple, just pass the path of the File as String, where your XML file is located.
eg:
File f = new File("d:\\Myfolder\\vivek.xml");
- You can always also use the following easy to use APIs to parse the XML.
JAXP & JAXB
CASTOR
Related
I want to parse a huge file in RDF4J using the following code but I get an exception due to parser limit;
public class ConvertOntology {
public static void main(String[] args) throws RDFParseException, RDFHandlerException, IOException {
String file = "swetodblp_april_2008.rdf";
File initialFile = new File(file);
InputStream input = new FileInputStream(initialFile);
RDFParser parser = Rio.createParser(RDFFormat.RDFXML);
parser.setPreserveBNodeIDs(true);
Model model = new LinkedHashModel();
parser.setRDFHandler(new StatementCollector(model));
parser.parse(input, initialFile.getAbsolutePath());
FileOutputStream out = new FileOutputStream("swetodblp_april_2008.nt");
RDFWriter writer = Rio.createWriter(RDFFormat.TURTLE, out);
try {
writer.startRDF();
for (Statement st: model) {
writer.handleStatement(st);
}
writer.endRDF();
}
catch (RDFHandlerException e) {
}
finally {
out.close();
}
}
The parser has encountered more than "100,000" entity expansions in this document; this is the limit imposed by the application.
I execute my code as following as suggested on the RDF4J web site to set up the two parameters (as in the following command)
mvn -Djdk.xml.totalEntitySizeLimit=0 -DentityExpansionLimit=0 exec:java
any help please
The error is due to the Apache Xerces XML parser, rather than the default JDK XML parser.
So Just delete Xerces XML folder from you .m2 repository and the code works fine.
I used the following code to filter files that are having the following extension
FileFilter fileFilter= new WildcardFileFilter("*.docx");
File[] sampleFiles= filesDirectory.listFiles(fileFilter);
But what if I want the opposite, I want to exclude files that are having this extension.
Currently I have the following code
public class FileFilter {
public static void main(String[] args) {
File dir = new File("C:\\temp\\filter-exclude");
File[] files = dir.listFiles(new ExcludeFilter());
for (File f : files) {
System.out.println("file: " + f.getName());
}
}
public static class ExcludeFilter implements java.io.FileFilter {
#Override
public boolean accept(File file) {
if (file.getName().toLowerCase().endsWith("docx")) {
return false;
}
return true;
}
}
}
But not sure if there are classes already for this.
Is there such a class?
You could compose with the notFileFilter:
dir.listFiles(
FileFilterUtils.notFileFilter(
FileFilterUtils.suffixFileFilter(".docx")))
There is not built-in FileFilter implementations that handle common cases such as yours.
To shorter you could use an anonymous class or better a lambda as FileFilter is a functional interface such as :
File[] files = dir.listFiles(f -> !f.getName().toLowerCase().endsWith("docx"));
As you're using commons-io already, have a look at NotFileFilter.
Given your use-case, an example looks like that:
FileFilter fileFilter = new NotFileFilter(new WildcardFileFilter("*.docx"))
File[] files = dir.listFiles(fileFilter);
Is there any specific reason you're not using the nio package and instead use the old io?
By using the nio package you can get your code to shrink considerably. Also you'll be using what is the best tools to operate with file and the filesystem in general. Have a look at the snippet below:
var matcher = FileSystems.getDefault().getPathMatcher("*.docx");
try {
DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("C:\\temp"), entry -> !matcher.matches(entry));
stream.forEach(path -> System.out.println("file: " + path.getFileName()));
} catch (IOException e) {
e.printStackTrace();
}
Effectively this does what your code does, using nothing but the out of the box API provided by the nio package to list directories and filter files based on their suffix.
I'm parsing in an xml file using SAX and need to add it as a resource instead of hard coding the file path.
I set up the file path y using a string like this:
private static final String GAME_FILE = "game.xml";
Its been suggested to use getResourceAsStream but I'm not sure how to apply that to my solution.
Does anyone how the reference the file from resources instead within the project?
This is how I reference the xml file by just adding it to the root of the project, which is bad practice:
public class Parser extends DefaultHandler{
private static final String GAME_FILE = "game.xml";
//You should have a boolean switch for each XML element, but not attribute
boolean location = false;
boolean description = false;
boolean item = false;
boolean gameCharacter = false;
boolean searchAlgorithm = false;
//Read in the XML file game.xml and use the current object as the SAX event handler
public void parse() throws ParserConfigurationException, SAXException, IOException{
XMLReader xmlReader = null;
SAXParserFactory spfactory = SAXParserFactory.newInstance();
spfactory.setValidating(false);
SAXParser saxParser = spfactory.newSAXParser();
xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(this);
InputSource source = new InputSource(GAME_FILE);
xmlReader.parse(source);
xmlReader.setErrorHandler(this);
}
Below shows the project structure after adding the file to a resources folder, but adding it to the resources folder, causes the file to not be found.
The problem is that game.xml is technically in the "resources" packages. Thus using
GAME_FILE = "/resources/game.xml"
InputSource source = new InputSource(getClass().getResourceAsStream(GAME_FILE));
should do the trick
I am trying to use FreeMarker to render some templates that come from a CMS path that happens to include a symbolic link (under Linux). Our CMS code handles the path to the template so, for example, this path:
/var/cms/live/display/main.html
really points to:
/var/cms/trunk/127/display/main.html
/var/cms/live is the base-directory while /display/main.html is the path.
In my case, live is a symbolic link -- in this case to trunk/127. FYI: the trunk is our SVN branch. When our CMS system downloads a new release of CMS files as (for example) trunk-128.zip, it unpacks it into trunk/128 and then changes the symlink (atomically) to trunk/128. Great.
The problem is that FreeMarker seems to have cached the trunk/127 path. It doesn't recognize that the file /var/cms/live/display/main.html has been updated and if the trunk/127 tree is removed, it generates a 500 error.
500 Unable to load template: /display/main.html
How can I get FreeMarker to cache the proper path?
The problem turned out to be with FreeMarker's FileTemplateLoader class. It does a baseDir.getCanonicalFile(...) call on the base-directory passed into the constructor. When our application booted, the base directory /var/cms/live gets resolved into the real path /var/cms/trunk/127/ by getCanonicalFile(...) so any future changes to the symlink are ignored.
It does this in the constructor, so we were forced to create our own LocalFileTemplateLoader which is listed below.
It is just a basic spring loaded implementation of TemplateLoader. Then when we are building our FreeMarker Configuration we set the template loader:
Configuration config = new Configuration();
LocalTemplateLoader loader = new LocalTemplateLoader();
// this is designed for spring
loader.setBaseDir("/var/cms/live");
config.setTemplateLoader(loader);
...
Here is our LocalFileTemplateLoader code. Full class on pastebin:
public class LocalFileTemplateLoader implements TemplateLoader {
public File baseDir;
#Override
public Object findTemplateSource(String name) {
File source = new File(baseDir, name);
if (source.isFile()) {
return source;
} else {
return null;
}
}
#Override
public long getLastModified(Object templateSource) {
if (templateSource instanceof File) {
return new Long(((File) templateSource).lastModified());
} else {
throw new IllegalArgumentException("templateSource is an unknown type: " + templateSource.getClass());
}
}
#Override
public Reader getReader(Object templateSource, String encoding) throws IOException {
if (templateSource instanceof File) {
return new InputStreamReader(new FileInputStream((File) templateSource), encoding);
} else {
throw new IllegalArgumentException("templateSource is an unknown type: " + templateSource.getClass());
}
}
#Override
public void closeTemplateSource(Object templateSource) {
// noop
}
#Required
public void setBaseDir(File baseDir) {
this.baseDir = baseDir;
// it may not exist yet because CMS is going to download and create it
}
}
im having a bit of issues calling a java file, i have created a java file
#ManagedBean(name="pdfSearch")
public class pdfSearch {
public String NewDestination;
public void main(String[] args) throws IOException {
File dir = new File(NewDestination);
String[] extensions = new String[]{"pdf"};// Add more file formats here to disply, could use this later on to display to the user all the files they have uploaded
System.out.println("Getting all .pdf files");
List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
for (File file : files) {
System.out.println(file.getCanonicalPath());
}
}
}
But i can not call this to run from a command button
<p:commandButton action="#{pdfSearch.main}" value="Search" ajax="False"/>
The filter.finder method is not a JSF Action method. That is meant to be a method of the signature
public String methodName()
That won't work in stock-standard JSF. I'd brush up on the JSF documentation for action methods.
Also you have written that you could use .toLowerCase(), if you wanted to search for files that are lowercase only. But this is not the case.
It will just make it see the letters as all lower case if you then wanted to order in them in lexiographical order for example.