I'm starting to build a JFrame application to work with File Handling. What I'm trying to get done from the application is that
it reads the contents of all the texts files in a particular location and merges the contents & creates one single text file.
The main property this application should have is that it should not have the navigate-to-location feature. Suppose if I paste this application in location C:\Users\Desktop\application.exe, the application must search the location for all the text files (i.e. on Desktop) & merge them into one single text file.
I've observed this in patch tools to patch softwares, they never ask for location for the software's_launcher.exe, they just tell us to paste the patch in the directory where the launcher belongs.
How do they do it? How can I do the same for my own application?
"./" is to specify current directory.
if you use
File f1 = new File("./");
then f1 is reference of current directory.
if your application is at C:\Users\Desktop\application.exe place then all files & folder at C:\Users\Desktop can access by "./" string
Related
I have a Spring Boot application that wraps the Eclipse BIRT reporting tool and runs as a Windows service via winsw. When a report with a chart generated by the engine is rendered, Spring Boot saves the image file in a folder it creates in the Windows/Temp directory. This folder and its contents persist across startups, which is less than desirable.
The application depends on a data folder that exists in a predefined location that exists for all installs of the software package. Given that, the ideal situation would be to create the folders in the package's data folder where it can be managed easily. Is there any way to accomplish this (preferably a method that allows the embedded Tomcat server to find and serve the files)?
Edit: Updated with results of response by #Magnus
The images in question are generated by the ReportEngine render process, so I think it's a BIRT thing not a Tomcat thing, but just to be sure I added server.tomcat.basedir=path/to/directory to my application.properties file. Still writes to Windows/Temp.
However, this reply got me thinking and i found that BIRT's EngineConfig has a setTempFolder method. Setting that to point at the desired folder (with the server.tomcat.basedir value in the properties file) results in BIRT doing work in the temp folder, but the generated images are still saved to the Windows\Temp directory.
Edit: Update 2
I was able to set the birt.viewer.working.path property in the EngineConfig and confirm that it was set by retrieving the value from the ReportDesignHandle (or maybe the ReportRunnable). With the changed value, the ReportEngine now does its work in the right directory, but still puts images into the Windows\Temp folder. Overriding the java.io.tmpdirproperty did nothing.
Edit: Update 3
This kind of works.. Setting the image folder location in the HtmlRenderOption results in the application not creating a folder for generated images in Windows\Temp (yay!). However, it is not putting the images in the location specified in the HtmlRenderOption, either (boo!), so i'm not really sure where to look so such image files can be cleaned up periodically.
Try to set imageDirectory in HTMLRenderOption.
HTMLRenderOption options = new HTMLRenderOption();
options.setImageDirectory("path/to/image/directory");
...
renderTask.setRenderOption(options);
see http://www.eclipse.org/birt/documentation/integrating/reapi.php
The embedded tomcat defaults to creating a directory in the temp directory specified by the java.io.tmpdir system property.
You can manually set the tomcat temp dir with the application property server.tomcat.basedir
Looking at the codebase there are a few places it deals with creating temp files.
From what I can gather the main place that the temp image directory is set si the ParameterAccessor class.
The logic is fairly complex but, it appears to default to ${birt.viewer.working.path}/report/images.
If the working path system property is not set, or the directory is not writeable then it will default to the java.io.tmpdir directory.
I would try setting the system property birt.viewer.working.path, make sure it is writeable.
If that doesnt work you might have to resort to overriding the java.io.tmpdir system property.
I've got a project to do with 2 other classmates.
We used Dropbox to share the project so we can write from our houses (Isn't a very good choice, but it worked and was easier than using GitHub)
My question is now about sharing the object stream.
I want to put the file of the stream in same dropbox shared directory of the code.
BUT, when i initialize the file
File f = new File(PATH);
i must use the path of my computer (C:\User**Alessandro**\Dropbox)
As you can see it is linked to Alessandro, and so to my computer.
This clearly won't work on another PC.
How can tell the compiler to just look in the same directory of the source code/.class files?
You can use Class#getResource(java.lang.String) to obtain a URL corresponding to the location of the file relative to the classpath of the Java program:
URL url = getClass().getResource("/path/to/the/file");
File file = new File(url.getPath());
Note here that / is the root of your classpath, which is the top of the directory containing your class files. So your resource should be placed inside the classpath somewhere in order for it to work on your friend's computer.
Don't use absolute paths. Use relative paths like ./myfile.txt. Start the program with the project directory as the current dir. (This is the default in Eclipse.) But then you have to ensure that this both works for development and for production use.
As an alternative you can create a properties file and define the path there. Your code then only refers to a property name and each developer can adjust the configuration file. See Properties documentation.
I would like to allow users of my program to open files only from a certain directory in the project folder. On Stack Overflow, I often find the following solution: chooser.setInitialDirectory(new File(System.getProperty("user.home"));, but I am trying to reference the resources folder in project. I tried to use fileChooser.setInitialDirectory(new File("/resources/")); but I get java.lang.IllegalArgumentException: Folder parameter must be a valid folder. How can I fix this problem?
The resources folder, and basically anything that becomes part of your deployed application, is not writable or browsable at runtime. Essentially, when you deploy your application, everything you need to run the application is bundled into an archive file, so resources is not really a folder at all, it's an entry in an archive. You cannot write to or browse such locations.
If you want the user to be able to save files to a specific location, you should define such a location: typically you would make this a subdirectory of the user's home directory. So, for example, you might do:
File recordsDir = new File(System.getProperty("user.home"), ".myApplicationName/records");
if (! recordsDir.exists()) {
recordsDir.mkdirs();
}
// ...
FileChooser chooser = new FileChooser();
chooser.setInitialDirectory(recordsDir);
I am trying to make a mess management application in Java using NetBeans. I want to save images of Members in a specified folder inside my src directory. I just created folder named EmpImgs for storing employees images. Here is my code:
File srcDir = new File(file); // current path of image
File dstDir = new File("src\\J_Mess_Mgnt\\EmpImgs\\"+Txt_C_G_M_M_ID.getText());
objm.copyFile(srcDir, dstDir);` // copy image from srcDir to dstDir
Here I use another class for copying images to predefined folders and renaming the images based on their ID.
Everything is working properly in Java IDE.
But unfortunately after making an executable .jar file, this code will not work. I cannot save or access any image file in that directory.
I just went through this site, but I didn't find a suitable answer.
All I need is saving and editing images inside jar folder
Hehe hi mate you need some help. This is a duplicate but I will cut you some slack and maybe you should delete this later. So back to basics, the jvm runs byte code, which you get from compiling java source code to .class files. Now this is different to C and C++ were you just get a .exe. You don't want to give your users a bunch of .class files in all these folders which they can edit and must run a command on the command line, but instead give them what is known as an 'archive' which is just an imutable file structure so they can't screw up the application, known as a jar in java. They can just double click on the archive (which is a jar), and the jvm will call the main method specified in the MetaInf directory (just some information about the jar, same as a manifest in other programming languages).
Now remember your application is now a jar! It is immutable! for the resasons I explained. You can't save anymore data there! Your program will still work on the command line and in IDEs because it is working as if you used your application is distrubuted as bunch of folders with the .class files, and you can write to this location.
If you want to package resources with your application you need to use streams (google it). BUT REMEMBER! you cant then save more resources into the jar! You need to write somewhere else! Maybe use a user.home directory! or a location specified from the class path and the photos will be right next to the jar! Sometimes you might need an installer for your java application, but usually you don't want to create the extra work if you don't need to.
At last I find an answer suit for my question.It is not possible to copy images or files to a executive jar folder.So I used a different Idea.Create some folders(as per our requirement),Where my executable jar folder is located(No matter which drive or where the location is).The code is..
String PRJT_PATH=""; //variable to store path of working directory.
private void getdire() throws IOException{
File f=new File(".");
File[] f1=f.listFiles();
PRJT_PATH=f.getCanonicalPath(); //get path details.for eg:-E:/java/dist
}
private void new_Doc_folder(){ //function for creating new folders
try{
String strManyDirectories="Docs"+File.separator+"Bil_Img"; //i need to create 2 folders,1st a folder namedDocs and In Docs folder another folder named Bil_Img
String SubDirectories="Docs"+File.separator+"EmpImgs"; //same as above but keep in mind that It will not create a Same folder again if already exists,
// Create one directory
boolean success = (new File(strManyDirectories)).mkdirs(); //create more than one directory
boolean success1 = (new File(SubDirectories)).mkdir(); //Creates a single directory
if (success && success1) {
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
It works Successfully.
Regds
I want to create an ini file to store some settings for my application. Is it a good idea to find where the jar file is located and create an ini file there? If yes, then how can I find the location of the jar file?
But if you know a better solution for something like this, I would like to hear some of them.
EDIT: I'm using mac and I want to run the same application in windows. I could write something in the System.getProperty("user.home") directory, but I want to keep the system clean, if the user decides to remove the app. There is no a better way to store the settings file, for example in the same directory with the application?
You can locate your application directory using the ClassLoader. See: Java: finding the application directory. Rather than an .INI file, use a .properties file - you can load and save this via the Properties class.
As others have noted, you should not write user settings to your application directory. What if the user does not have write access to the application directory? What if your application is being used by multiple users on the same system at the same time? Neither of these situations are unusual, even on Windows.
You might still want to load some settings from the application directory - perhaps the administrator has configured default settings there.
A common convention is to save user settings to the user's home directory:
/home/user/.eclipse
C:\Documents and Settings\User\.eclipse
Although this means you might leave stray files behind, this can be beneficial if the user re-installs the app. Document such things in a README. Here is how to create and get a reference to the directory:
public static File getSettingsDirectory() {
String userHome = System.getProperty("user.home");
if(userHome == null) {
throw new IllegalStateException("user.home==null");
}
File home = new File(userHome);
File settingsDirectory = new File(home, ".myappdir");
if(!settingsDirectory.exists()) {
if(!settingsDirectory.mkdir()) {
throw new IllegalStateException(settingsDirectory.toString());
}
}
return settingsDirectory;
}
On unix-like operating systems, starting the directory name with a period (".myappdir") will make the directory hidden. On Windows, it will be located below My Documents, so users will not see the directory unless they go looking for it.
If the settings are only written by your application (rather than edited manually), consider using the Preferences API.
You should not be storing temp files in the install directory of an application. Remember, the user running the application may not have write access to that directory. The safest place to put stuff like that is in C:\Documents and Settings\username\Application Data\ApplicationName folder (adjusting the name as necessary).
That said, however, I would probably store that type of stuff in the registry instead of a file on their computer. (But, that's just me.)
Typically Java programmers don't use .ini files, but .properties files (different format). You can use the java.lang.Properties class as a nice programmatic wrapper if you do.
While you can get the location of your jar file by calling getProtectionDomain().getCodeSource().getLocation() on your class's .class member, I do not recommend that you do this.
I would instead write the file to the System.getProperty("user.home") directory - the users' home directory, or if it is truly temporary, System.getProperty("java.io.tmpdir")
It depends whether your ini needs to be human readable/writable under normal circumstances. If not, you can use a properties file rather than an ini file, and store it in the "user" directory.
As for finding the jar file, you would have to find the ClassLoader for a class known to be loaded from the jar, check that it was the appropriate type of ClassLoader (ie that it's really been loaded from a jar), and you can extract the path from that. I can probably dig out the code to do this if that's really what you want. I wouldn't necessarily recommend it.
EDIT The user.home property will give you the user directory, which you can safely use.
The idea with the .properties file instead of the INI file is good. Also, if you store some sensitive data in there, you may consider encrypting it. Check this out:
https://www.owasp.org/index.php/How_to_encrypt_a_properties_file
or this:
encrypt and decrypt property file value in java