Search code examples
javafxfilepath

How to create .xml File in JavaFx


How can I create .xml File in my app folder, and save some data to it ?

    public void saveRoomDataToFile(File file) {
try {
    JAXBContext context = JAXBContext
            .newInstance(RoomListWrapper.class);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    // Wrapping our room data.
    RoomListWrapper wrapper = new RoomListWrapper();
    wrapper.setRoomData(RoomData);

    // Marshalling and saving XML to the file.
    m.marshal(wrapper, file);

    // Save the file path to the registry.
    setRoomFilePath(file);
} catch (Exception e) { // catches ANY exception

}
}

This part of code is for saving data to file, and it woorks. I would like to when app is started for the first time that the .xml file is created in app folder, and that I can edit its data.

For example if I have this folders:

  1. folder
  2. folder.res
  3. folder.controller
  4. folder.view
  5. folder.model
  6. folder.data

I would like to save it to folder.data. How to get that file path ?

    private void handleSave() {
    File roomFile = new File("");
    if (roomFile != null) {
        homeAutomation.saveRoomDataToFile(personFile);
    } else {
        System.out.println("Error !");
    }
    }

This is function that handles save button. Note that there is no file path.


Solution

  • Try this function to obtain the path: example returnPathFile("/data/yourfilename.xml");

    public String returnPathFile(String filename){
       String path=getClass().getResource(filename).getPath();
       path=path.substring(6);
       int p=path.lastIndexOf("/dist/");
       if (p>0){
          path=path.substring(0, p);
          path+="/src"+filename;
       }
       return path;
    }