0

Hi I was wondering how to access files in the project folder in java/maven, i have thought about using src/main/resources, but i have been told it is a bad idea to write to files in this directory, and should only be used in configuration for the project, So i have created a new non source folder but i was wondering if there is a way to access this file in java without giving an absolute path, as i need to use it in different env. any help or other suitable suggestions would be great here thanks. i will be writing to the files at runtime.

EDIT:

i am using this to acces the file:

private static final String ACTUAL_VALUES ="verification/actualCounterValues.csv";

where verification is a folder i have created in my project

smurfMT
  • 124
  • 10
  • What do you mean with "different environments"? Just Java SE? JEE? It would of course be possible to use a Java Content Repository, but this will likely be too much for a small application. – nils Apr 29 '14 at 12:36
  • If you need to use code in different environment then you need to access the files using "relative paths". What seems to be the problem? – Hirak Apr 29 '14 at 12:38
  • I mean Linux/windows for different env, @Hirak i ment absolute paths not relative see edit – smurfMT Apr 29 '14 at 12:44
  • You can use private static final String ACTUAL_VALUES ="verification"+File.separator+"actualCounterValues.csv"; – Hirak Apr 29 '14 at 14:38

1 Answers1

1

As i understand you, your goal is to access a file from within your app, without hardcoding a relative path because you're going to run it on different environments.

The first thing you may have to solve is to decouple the file-reference from your app - because if you move your app it must adapt to the new environment. You may solve that by putting an absolute file-reference into the system-environment (which is accessible through the System.getenv() method). Another way could be to deliver the file-path as command-line-argument.

After that you have to specify when which running instance of your app will access the file. If your application runs separated in the maven and a production environment - everything is fine with using relative paths in the maven-project. The production-app will then generate and use its own file in its environment.

If they must share the file, you have to provide physical access from both environments to that file-path, after that you may access that file with separate absolute paths (delivered through cli-args or system-properties) or with "hard coded" relative paths, which access a file-link (which point to that absolute file).

But i must discourage you from using any hardcoded configuration-specific variables for ongoing maintenance reasons.

And if these two application-instances will access both one single file, you should also be aware of possible concurrency difficulties (especially in the filesystem - see that post).

Community
  • 1
  • 1
Florian Neumann
  • 5,587
  • 1
  • 39
  • 48