I am maintaining a Spring Boot project. There is this code:
BufferedReader reader = new BufferedReader(new FileReader("./setting_mail_sender.txt"));
Where should the file be located in this case?
In 'the current working directory'. And where is that? Who knows!
Whomever wrote that code messed up. It's not a good idea to use the CWD for anything in any java code unless you specifically know you want it. And generally, that's only the case when you're writing command line tools in the vein of the various tools you find in your average linux distro's /bin dir - a rare occurrence, given that the JVM isn't really designed for that kind of thing.
There are 3 different best practices for 'data files' depending on the nature of the data:
Static, unchanging data - as much part of your app as your class files are. These should be loaded with MyClass.class.getResource("name-of-resource.txt") and shipped the same way your classes are. For example, inside the jar file.
Config files. These should usually be in System.getProperty("user.home") - the user's home dir; /Users/yourusername on macs, /home/yourusername on linux, C:\Users\YourUserName on windows. Best practice is to ship a 'template' version of the settings file if relevant in the jar file, and upon detecting that there is no config file present at all, to write out the template (and you load the template in via MyClass.class.getResource). If a template is not a good idea, something in a similar vein. Bad practice is to have the installer do this, and have your app be broken or leave the user having to peruse complex documentation to (re)create the config file. A different way to do it right is to have a config page in your app (a window, menu bar setting, web app thing - something with a user interface) where you can change settings and the config file is simply the way you store that data.
Changing data files. For example, you ship H2 (an all-java database engine) with your app and it needs to write its database file somewhere. This is a bit tricky; user home is not the right place for such data files, but you can't really 'find' the dir where your app is installed either. Even if you can, on non-badly-designed OSes, apps usually cannot (and should not!) be able to write to that location anyway. The location where this data is stored should definitely be configurable, so one easy way out is to require that the user explicitly picks a place. Otherwise I'm afraid you're stuck having to write per-OS code - find /Users/myusername/Library/Application Support/yourappname on mac, which is the right place. As far as I know there is no library to do this right.
None of them involve 'require that the user start the app with the right CWD'. There are good reasons for that: It can be hard to configure, and it's not something users think of to configure. For example, when setting up a java app as a recurring task in windows, you can configure the working dir for such a process, but it's not something that's usually considered as crucial configuration. When running a java app from the command line, who knows what the working dir is. You'll end up with an app that usually works, except in some circumstances when it magically doesn't, and most of your users have no idea that the difference between the magic run that works and the one that does not, is the directory they were in when they started the java app.
If you can edit that code, do so - figure out which of the 3 different kinds of data this is about (sounds like the second bullet: Config stuff, so should be in user home, and the app's name should be part of the file name) - and fix it. for example, that should be:
try (var in = Files.newBufferedReader(Paths.get(System.getProperty("user.home"), "myapp-mail.conf")) {
}
This solves a whole bunch of problems:
Uses try-with to avoid resource leakage.
Reads from user.home, avoiding current working directory as relevant setting.
Actually uses UTF-8 encoding (whereas your code will, at least until java 17, do 'platform default'. It's somewhat unlikely you want that, as it means your config file is not portable; copying it from one computer to another may break things. You presumably don't want this.
If errors occur, the error messages are improved (one of the downsides of the 'old' file API).
If you can't change this code, figure out what the CWD is; put the files there, and ensure that, however you start this spring boot project, you always start it from that directory. If you can't change this code but you can run some code in that JVM, you can print it: System.out.println(Paths.get(".").toAbsolutePath()) will show it to you.
Related
I've been trying to make jar application that can read a csv file in the same directory as it. This is, however, proving difficult as my means for accessing the file currently is:
InputStream is = getClass().getClassLoader().getResourceAsStream(filename);
Which works for my program running in the IDE and for my tests but doesn't work when I run the program from the compiled jar file. I have no idea how to get it to work for both. I seriously can't understand this path stuff, it seems like there are a million ways to do it and only one of them work for only one specific scenario.
I've been trying to make jar application that can read a csv file in the same directory as it.
Ah, there's your problem. That just isn't a thing.
There are only 2 types of files:
Application Resources
These are read only, and are as much part of your app as your class files are. It is not in any way relevant to think about 'editing' them - that's not the kind of thing they are. It is reasonable to assume that if this resource is somehow missing, the app is as corrupt / misinstalled as it would be if class files are missing.
For this, you use .getResource and .getResourceAsStream. And note that getClass().getClassLoader() is wrong, you want MyClass.class.getResource and then add a slash if you want to go from root (because getClass() potentially breaks when you subclass, and going via classloader is [A] just typing for no reason, and [B] breaks in bootload scenarios. MyOwnClassName.class.getResource never breaks, so, always use that).
This asks java to look in the same place class files are and nowhere else. Your class files are inside the jar files, and not next to them, therefore, it won't find a text file that is sitting next to jar files.
it does not make sense that it does work during development: That means you shoved a file inside the resources folder, which is equivalent to having a CSV file inside the jar file. You must have gone out of your way to tell your build system to do weird things. Don't do that.
If that CSV file is not intended to be user editable it should be inside the jar file and not next to it: That makes it an application resource. Examples of application resources:
You have a GUI, and you need to store the icon files and splash screen art and such someplace.
You ship static data with your app, such as a table of all US states along with the zipcodes they use (could be a text or csv file for example).
Templates of config files. Not config files themselves.
DLLs and the like that you need to unpack (because windows/linux/mac isn't going to look inside jars for them).
You're a webapp and you want to ship the HTML static files along with your webapp.
If this is what your CSV file is, the fix is to put it in the jar, not next to it, then load it with MyClass.class.getResource(name).
Config files and project files
For example:
For a rich text editor (like, say, LibreOffice Writer), the .odt files representing your writings.
Save games for a game.
A config file, which can be edited by the user, or is edited by your own app in a 'preferences' dialog. This stores for example whether to open the app full screen or not, or authentication info for a third party API you're using.
These should not be in the jar, should not be loaded with .getResource at all, and should not be in src/main/resources in the first place.
They also should not be next to your jar! That's an outdated and insecure model (the idea that editable files sit in the same place the app itself sits): A proper OS configuration means that an app cannot write to itself which is most easily accomplished by having it be incapable of writing to its directory. Some OSes (notably, windows) did this wrong for a while.
For example on windows, your app lives in C:\Program Files\MakorisAwesomeApp\makori.jar, and the data files for it live somewhere in C:\Users\UserThatInstalledIt\Documents\MakorisAwesomeApp.
oh linux, your app might be /usr/bin/makori and the data lives somewhere in the home dir. Config data might live in /etc/.
You don't "ship" your config files, you instead make installers that create them. You can do this part in-app by detecting that the relevant config file does not exist, load in a template (that is a resource, shipped inside your jar, loaded with getResource), and write it out, and tell the user to go look at it and edit it.
I really want a CSV file next to my jars!
Well, that's wrong, so, there are no libraries that make this easy. When you want to do silly things its good that APIs don't make that easy, right?
There are really hacky ways to do this. You can use .getResource to get a URL and then 'parse' this. This breaks the classloader abstraction concept (because in java, you can write your own classloaders and they can load from anywhere, not just files or entries in jars), but you can ask for 'yourself' (MyClass.class.getResource("MyClass.class")), pull the URL apart and figure out what's happening - does it start with file://? Then it is a file, so turn it into a j.i.File object, and go from there. Does it start with jar://? find the !, substring out the jar part, and now you know the jar. Make that a java.io.File, ask for the parent dir, and look there for the CSV.
You have to write all this. It's complicated code that is hard to test. You should not do this.
I am making a custom file explorer in java. I came to know of this worm which starts executing when the file icon is viewed in file explorer. I believe, this could be possible only if it is loaded into memory somehow by something like reading of metadata (Please correct me if i am wrong). I have heard java is a 'safe' language but just wanted to know how much safe it is.
I am using the following imports in my program :
java.io.File;
java.net.URL;
java.nio.file.Path;
javax.swing.filechooser.FileSystemView;
I use fileSystemView.getFiles() to get files list and simply display an icon by checking the file extension.Files are not preveiwed also.
So if i disable opening of a file by clicking on its icon in my file browser, then is there any way that some malware can run when my file explorer program displays the contents of an infected pendrive?
Can this be achieved by other programming languages also?
There are several aspects to you question here.
First of all, about the danger of accidentally reading/executing files by clicking them in your application: I think it's a bit difficult to answer that without actually seeing the code you're running. I can't see any obvious threat based on your description, but then again, I don't know exactly what your Java Runtime will do for you when you mark a file, read the directory it is in, and read the file itself - if there's no "magic" happening behind the scenes there, there might not be a problem. If Java does any kind of reading/parsing/whatever with a file in order to register and list it though, it's hard to tell.
From the documentation for Class FileSystemView
Since the JDK1.1 File API doesn't allow access to such information as root partitions, file type information, or hidden file bits, this class is designed to intuit as much OS-specific file system information as possible.
I'm not really sure exactly what this even means, but I take it as an indicator that something is going on behind the scenes when accessing files. Perhaps someone with more in-depth knowledge can add to this.
Now as for using this to analyze potentially infected thumb drives: Be very careful.
When you connect something to your USB, it can do "stuff"(*) automatically as soon as it is connected. This will likely happen long before you've even started your Java app, so it won't really matter how safely you code it.
There are ways to restrict access to USB, and such auto-run behavior. You should at least be aware and look into this, and make sure you have an updated and working security scanner of some kind before inserting anything suspicious into your PC.
(*) There are even examples where USB devices can steal info from locked computers by providing a (fake or real?) network connection, and then listening in to and manipulating the automatic connections computers typically do continually in the background.
I have been coding for about a month and I have found ways to adapt around ever problem but one. The problem as you can probably see by the title is how to make a way to make game saves. I am currently creating a very simple game that has about 5 classes of my code and maybe 2 of Java Swing GUI.
I know how I would like to go about the saving process but I have no idea how to do it in my code. How I would like to go about doing this is by making the code print a Number or Integer to a file to represent a Level. For example if you completed level 1 the number in the file would be 1. I have tried some templates for this but none of them work.
I understand how to write to a file but my problem is reading it from a jar or even creating a file then reading it from a place on the computer. I need to know how to find a file URL for different computers because some use Docs and Settings and other Users. Please could someone help.
Since the jar is read only, it can only contain the 'default settings'. See this answer for the general strategy to deal with such a embedded-resource.
Speaking of which (embedded resources) see the info. page for more details on how to access them.
Here is an example of storing and reading a Properties file from the 'current directory'.
As mentioned by #MadProgrammer though, it is safest to put the settings file into a (sub-directory) of user.home, as seen in this answer.
But a properties file is just one option. You might also serialize an object, or write the file in a custom format that your app. knows how to read, for the first two off the top of my head.
Besides 'serialize (in some form) in a File', there is also the Preferences API, or for desktop applications launched using Java Web Start, the PersistenceService. Here is a demo. of the service.
I need to know how to find a file url for different computers because
some use Docs and Settings and other Users
The System property user.home points to the user's home directory
File userHome = new File(System.getProperty("user.home"));
I'm making a game, in Java, that has these following important features:
1) Connects to a remote Server (which i made), and will check for updates and install them if necessary
2) is NOT A SINGLE .JAR FILE (ie. has multiple .jar's and other things, such as .png, .wav, etc)
3) JAVA WEB START IS NOT AN OPTION, AS I WANT TO MAKE THIS ALL MYSELF
keeping the things above in mind, i have run into a problem. i have no clue how to implement a multiple "patch" update system. currently i have 1 .txt file, that the server reads from, and sends the files listed in the .txt to the client, which then moves them into place. The problem is, that is only useful for maybe 2 updates. I'm looking for a more useful, long term solution, and i need some help. here are some of the things i've thought of:
1) have a zip folder named after each version (problem: how would the client get ALL of the most updated files
2) have a .txt file INSIDE of each jar containing the version (problem: cant do that with png's or wav's, and i dont know how i would read the txt file to begin with)
i really need some help, i've tried googling it, i've thought about it for going on 3 weeks now, and cannot think of anything.
QUESTION: how would i make a game/program update with multiple patches?
Firstly, the best solution by a long, long way is to use Webstart / JNLP.
But if you insist on not using it (for whatever reason then) then it is technically possible. However:
It is messy and complicated.
It will either be very inefficient ('cos you have to load the entire program each time the user), or the user has to trust you enough to install your program with permissions that will allow it to install random stuff on his machine without notice.
The way to do it is to split the game into a launcher part and an application part. The launcher needs permissions to write and delete (non-temporary) files, and fetch stuff from the internet. It "calls home" to find out the latest version(s) of the application files, and then downloads and installs them. It has to cope with all sorts of error conditions, and it needs to make sure that nothing can trick it into installing bad stuff on the user's machine, etcetera, is someone spoofs your update service.
Of course, JNLP takes care of all of this, and lots more besides. People are going to be more willing to install the JNLP infrastructure that yours ... which might be insecure, or actively nasty (for all they know). (I for one wouldn't install a self updating application on my machine unless it was supplied by a company with impeccable credentials.)
I think you need here JNLP framework.
JNLP provides followed things:
allows to user to download jars from server
on launch verifies if application need to update
runs on local JVM
Actually, every java application you can convert to JNLP. Just to sign on all jars that your game contains, create executable jar from your game and create single Web page from where you can download your game
I am developing a small game in Java and I am shipping it as a single Jar file. I want to store the high scores/best times for that game somewhere. Instead of storing it in a separate file, I would like to store it in the application itself (inside the Jar) so that its not lost. Is this possible at all ? If so, how to do it programatically.
Java does not give you tools to modify the JARs which are currently run. If you really want to do it, you have to guess the location of the JAR by yourself (which might reside on a read-only filesystem) and modify it the same way you would modify any archive file.
Bottom line: it's a very bad idea, don't do it! See this question for a much more reasonable solution.
Nothing is impossible, but storing it in the jar file would make it very complicated. You might also end up with unwanted side effects like "Permission Denied" errors when the jar is owned by another user. Virus scanners might get nervous when they see jar files change without reason, etc....
I would look to the Preferences API for storing this kind of info.
I think it is a bad idea to try and store anything in the jar file. Another option is to have a web based service offered to the people playing with your game. The game could connect through a web service to your hosted server and then store everything centrally there. Not sure if it is exactly what you want but it's just an idea. It would also allow people to compete with each other.
Java JAR file is a ZIP-Archive, so you could possibly access it with standard ZIP-Tools and just extract one hisghscores.txt file, modify it and then pack it back again.