Mr37037
Mr37037

Reputation: 748

writing to file in maven project

Hi i am using maven web project and want to write something to file abc.properties. This file in placed in standard /src/main/resource folder. My code is:

FileWriter file = new FileWriter("./src/main/resources/abc.properties");
            try {
                file.write("hi i am good");
            } catch (IOException e) {
                e.printStackTrace();

            } finally {
                file.flush();
                file.close();
            }

But it does not work as path is not correct. I tried many other examples but was unable to give path of this file.

Can you kindly help me in setting path of file which is placed in resources folder.

Thanks

Upvotes: 1

Views: 3550

Answers (2)

tmarwen
tmarwen

Reputation: 16364

If your file is dropped under src/main/resources, it will end up under your-webapp/WEB-INF/classes directory if you project is package as a Web application i.e. with maven-war-plugin.

At runtime, if you want to files that are located under the latter directory, which are considered as web application resources, thus are already present in the application classpath, you can use the getResourceAsStream() method either on the ServletContext or using the current class ClassLoader:

From current thread context:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is = classLoader.getResourceAsStream("abc.properties");
FileWriter file = new FileWriter(new File(new FileInputStream(is)));
// some funny stuff goes here

If you have access to the Servlet context:

ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/abc.properties");
FileWriter file = new FileWriter(new File(new FileInputStream(is)));
// some funny stuff goes here

Notice the leading slash in the latter example.

Upvotes: 0

Robert Scholte
Robert Scholte

Reputation: 12345

I think you're confusing buildtime and runtime. During buildtime you have your src/main/java, src/main/resources and src/main/webapp, but during runtime these are all bundled in a war-file. This means there's no such thing as src/main/resources anymore. The easiest way is to write to a [tempFile][1] and write to that file. The best way is to configure your outputFile, for instance in the wqeb.xml.

[1]: http://docs.oracle.com/javase/6/docs/api/java/io/File.html#createTempFile(java.lang.String, java.lang.String)

Upvotes: 1

Related Questions