Reputation: 632
In my java program, I want to write files to a folder inside my current package. If this folder doesn't exist, I will create it.
How do I refer to this maybe non-existent folder with relative path, so that if I move my package around, I don't have to manually fix the path?
private void writeFamilyPerFile(String name, ArrayList<String> planNames) {
File file;
File folder = new File(OUTPUT_DIR + "/temp/");
BufferedWriter bw = null;
try {
if(!folder.exists()) {
folder.mkdir();
}
file = new File(folder + name + ".md");
file.createNewFile();
bw = new BufferedWriter(planNames);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException ignore) {
}
}
}
}
OUTPUT_DIR
is the path to my current package, and folder
is the folder I want to create inside current package directory.
UPDATE
Thanks everyone for answering my question. I'm not very experienced, so is making a lot mistakes.
I'm generating a bunch of markdown files, which could be used as is, and will be processed further later in my app, i.e., merged into 1 single file, and translated into HTML. My app lives inside a project, the file structure is like this:
root
|--other parts
|--definitions
| |--definition
| |--java
| | |--validator
| | |--docGenerator
| |--pom.xml
|--pom.xml
docGenerator is my project. Where should I put:
Big thanks to everyone!
Upvotes: 2
Views: 1942
Reputation: 718698
It is very unclear from your Question what you are trying to do. However, I think that this is what you are asking for:
...
File outputDir = new File(OUTPUT_DIR);
File outputFile = new File(outputDir, planNames.get(i) + ".md");
bw = new BufferedWriter(new FileWriter(outputFile));
...
The above opens a file (named planNames.get(i) + ".md"
) in the directory OUTPUT_DIR
. The file is opened for writing as a text file. It will be created if it doesn't exist already, and truncated if it does exist.
This assumes that the output directory already exists, and that OUTPUT_DIR
is a String
whose value is a resolvable pathname for the directory.
I should also point out that writing files into the project source tree in your IDE is not going to work if your application even needs to run outside of an IDE. (And this is a strange thing to do inside an IDE too ... unless you are generating Java source code.)
In that sense, you are probably asking for the wrong thing; i.e. something that doesn't make sense. If you told us what you are actually trying to do here, we could suggest alternatives that made more sense.
Upvotes: 0
Reputation: 1431
Well assuming your current path is within the application folder (where your package folders are), and your class files are not within a jar, you can do this.
String OUTPUT_DIR = this.getClass().getCanonicalName().replace(".","/");
OUTPUT_DIR = OUTPUT_DIR.substring(0,OUTPUT_DIR.lastindexOf('/'));
Upvotes: 1