Java create a folder in current package folder - java

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:
intermediate generated files, which I'd like to keep
temp files I will generated, use and delete
final output files
resource files my program read and use
Big thanks to everyone!

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('/'));

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.

Related

How to Write Output Files from a JAR Program to Directory Outside the JAR?

tl;dr I'm more used to writing command-line scripts that can just output based on the current working directory, so I'm unsure what directory to use for output files in a program that will be launched from a JAR.
Program Description:
My program builds an HTML file from data given to it from the rest of the program, and then is supposed to write it to a file that we'll call "Output.html" for simplicity.
Relevant Code:
public void outputHTML()
{
String output = buildHTML();
// Expanded to explain my confusion better
String fileDirectory = ""; // ???
String fileName = "Output.html";
String fullPath = fileDirectory + "\\" + fileName;
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fullPath)))
{
writer.write(output);
writer.close();
} catch (IOException e)
{
System.out.println("File not found.");
e.printStackTrace();
}
}
Problem
I don't know what to put the file directory as. Usually I run my programs from the command line and use ".\\Output.txt" as my output path, but I don't know where to put it if it's being run from a JAR.
The desired file structure is as follows:
Encompassing Folder
Program.jar
output
Output.html
Or alternatively (not sure if this makes it easier to understand or harder):
main\
main\Program.jar
main\output\
main\output\Output.html
Everything I can find on SE only relates to reading files that are both immutable and internal, but I'm trying to output a non-static file to a location outside of my jar.
Can anyone help with this? Thanks!
Misc Details
I'm using Eclipse without Gradle currently, because I don't know what Gradle is and new things are scary. If this particular problem would be easier to solve with Gradle, let me know and I'll look up more about it.
EDIT:
Added syntax highlighting to code block.
Formatted everything a bit better
Changed title to be more descriptive
You can use an absolute path: e.g. fileDirectory = "\\project\\test\\main\\output";
using normal slash should also work even on Windows ("/project/test/main/output")
Or use a relative path - this will start from the current working directory (user directory), the one where the JVM was started in - e.g. fileDirectory = "main\\output";

Copying File In Current Working Directory is Not Working

private void copyFile() throws IOException {
Path destination;
String currentWorkingDir = System.getProperty("user.dir");
File fileToCopy = component.getArchiveServerFile();
if (path.contains(File.separator)) {
destination = Paths.get(path);
} else {
destination = Paths.get(currentWorkingDir + File.separator + path);
}
if (!Files.exists(destination)) {
try {
Files.createDirectories(destination);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
FileUtils.copyFileToDirectory(fileToCopy, new File(destination.toString()));
}
}
Basically what I'm trying to do here is copying a file in some location using the path provided in the class's constructor. The logic is like this:
If the path has file separator, I consider it a full path and copy the file at the end.
If the path doesn't have file separator, I copy the file in the working directory from which the .exe file was launched.
So far, only the first option works (the full path). For some reason, the working directory option is not working and I can't figure out why.
UPDATE: If I just change the following line:
String currentWorkingDir = System.getProperty("user.dir");
to
String currentWorkingDir = System.getProperty("user.home");
It works. So I'm guessing the problem is coming from user.dir? Maybe at runtime, the folder is already being used and as a result, it can't copy the file into it?
The weird thing is, I don't have any exceptions or error, but nothing happens as well.
UPDATE 2: I think the problem here is that I'm trying to copy a file which is embedded in the application (.exe file) that I'm executing during runtime, and java can't copy it while the current working directory is being used by the application.
UPDATE 3:
Since this copy method is used in an external library, I had to come up with another way (other than logs) to see the content of system property user.dir. So I wrote I little program to create a file and write in it the value return by the property.
To my surprise, the path is not where my application was launched. It was in:
C:\Users\jj\AppData\Local\Temp\2\e4j1263.tmp_dir1602852411
Which is weird because I launched the program from :
C:\Users\jj\workspace\installer\product\target\
Any idea why I'm getting this unexpected value for user.dir?

Java: store configuration variables in a file

I'm developing a program with NetBeans 8.0 and JavaFX Scene Builder 2.0 that need store some variables in a file, where admin users can modify it when needed, (like change server IP address, or a number value from a no editable textfield) and if they close and load again the program, the changes made in variables are kept. Like any settings section of a program.
I just try do it with the Properties file, but i have problems to store it in the same folder as .jar file. When the program execute the line new FileOutputStream("configuration.properties"); the file is created at root of the disk. As the folder of the file can be stored anywhere, i not know how indicate the right path.
Creating the properties file in the package of the main project and using getClass().getResourceAsStream("configuration.properties"); i can read it but then i can not write in for change values of variables.
Is there a better method to create a configuration file? Or properties file is the best option for this case?
My other question is whether it is possible to prevent access to the contents of the file or encrypt the content?
PD: I've been testing this part of the code in Linux operating system currently, but the program will be used in Windows 7 when ready.
If you use Maven, you can store your property files in your resources folder, say resources/properties/. When you need to load them, do this:
private Properties createProps(String name)
{
Properties prop = new Properties();
InputStream in = null;
try
{
in = getClass().getResourceAsStream(name);
prop.load(in);
}
catch (IOException ex)
{
System.err.println("failed to load \"" + name + "\": " + ex);
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
System.err.println("failed to close InputStream for \"" + name + "\":\n" + FXUtils.extractStackTrace(ex));
}
}
return prop;
}
Where name is the full path to your properties file within your resources folder. For example, if you store props.properties in resources/properties/, then you would pass in properties/props.properties.
I am not 100% sure if you can carry over this exact procedure to a non-Maven project. You'd need to instruct whatever compiler tool you are using to also include your property files.
As far as your final question goes, in regards to encrypting your properties, I would consider posting that as a separate question (after having done thorough research to try to discover an existing solution that works for you).
At last i found how obtain the absolute path from folder where is .jar file to create properties file in, and read/write it. Here is the code:
File file = new File(System.getProperty("java.class.path"));
File filePath = file.getAbsoluteFile().getParentFile();
String strPath = filePath.toString();
File testFile = new File(strPath+"/configuration.properties");
Tested in Ubuntu 13.04 And Windows 7 and it works.
For encrypt the properties values i found this thread that answer how do it.

Write to a .txt file in a package

I would like to write to a .txt file that is inside a package. I can get it to read from the exact location the .txt file is stored but not from inside the package. I'm assuming it is using class loaders but I cannot seem to get it to work.
Here is what I have so far.
public void writeFile(String fileLocation) {
Writer output = null;
File file = new File(fileLocation);
try {
output = new BufferedWriter(new FileWriter(file));
output.append("WRITING TEST");
output.close();
} catch (IOException ex) {
System.out.println("Couldn't write to file.");
}
}
Then I use this in another class to write.
WriteFile writeFile = new WriteFile();
writeFile.writeFile("src/com/game/scores.txt");
I understand that if using class loaders you remove "src/" because that will no longer exist when the program is compiled in a .jar.
It is not possible to write or update a file inside jar. Since jar itself is a file.
Please refer this link.
Write To File Method In JAR
You could use a class in that package to give you the location of the folder.
Try something like
public URL getPackageLocation() {
return getClass().getResource(".");
}
This should give you the location of the folder from which this method is being called from.
From the comments you already know that you cann't write to a file, which resides in a JAR file. At best what you can do, is creating your file, relative to the path where the JAR is located like bellow:
mylocation
|-- my-jar.jar
|-- com
|--game
|--myfile.txt
I would like to write to it to update the scores in my game as the
user goes through the levels.
While it might be possible to write to the JAR file, I don't recommend it for this use case. Just write it somewhere at:
Path userdir = Paths.get(System.getProperty("user.home"), ".myApp", "<my app version>");
You can't write into Jar file. Writing into Jar file is not recommendable. You can write outside the jar file.
Please refer this and this stack overflow question for more details.

How to set file path to src folder of project

I want to make a program that you can email to someone and they can run it.
Right now my code for making a file is like this:
File f = new File("/Users/S0urceC0ded/Desktop/Code/project/JavaStuffs/src/axmlfile.xml);
f.createNewFile();
But what if someones username is not S0urceC0ded, or they put the project in a different place? How could I set the file path to the src folder plus the filename?
Leave the path off entirely, it will use the directory of the project.
Change
File f = new File("/Users/S0urceC0ded/Desktop/Code/project/JavaStuffs/src/axmlfile.xml");
To
File f = new File("axmlfile.xml");
I generally use code like this for temporary file storage, this way it gets cleaned up when the application finishes. If required you can allow the user to save a version of the file or move it to a permanent location.
try{
//create a temporary file
File temp = File.createTempFile("axmlfile", ".xml");
System.out.println("Location: " + temp.getAbsolutePath());
}catch(IOException e){
e.printStackTrace();
}

Categories

Resources