Domanda

I am trying to programmatically build html pages that uses the same css. In order to do that I am creating necessary directories and a the css file.

As the picture below shows I have the css file in my package "resources" and I want to take it and write a local copy when I call the method writeCss

enter image description here

This is what the method looks like:

private void writeCss(){
        try {
        BufferedWriter out = new BufferedWriter(new FileWriter("new_project/css/style.css"));
            //take the style.css from the package resources

            //write the css to a local file
            out.write("");

            out.close();
        } catch (IOException e) {}
    }

I first thought just to copy and paste the entire CSS code into the out.write("") but the code is too long for the buffer.

Please suggest.

È stato utile?

Soluzione

The easiest way would be:

Files.copy(Gui.class.getResourceAsStream("style.css"),
    Paths.get("new_project", "css", "style.css"));

Altri suggerimenti

You may read the contents of the file using a classloader to help you finding the file, for example:

InputStream is = getClass().getResourceAsStream("/resources/style.css");

Please note that if the classloader is unable to find the file it will return null, but I think it will work just fine in your case. Normally you would read through the entire file using a buffer and then writing it straight to an output stream until the input stream gets consumed, no need for a writer if you wont modify or process the CSS file before writing it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top