I am doing the following,
String str = "this is the new string";
URL resourceUrl = getClass().getResource("path_to_resource");
File file = new File(resourceUrl.toURI());
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(xml);
writer.close();
In the above code I am trying to write to a resource file contained in one of my java packages. After executing the code, my program executes fine but the file just updates the properties file in web-INF and not into the package where it is stored. Can anyone please help me figure how can I achieve that or what am I doing wrong here? Thanks a lot.
You should not be trying to write to a file stored with your application classes. Depending on the application server, the location you are trying to write to may not be writable or the application may be running from an application archive (a .war file).
You should use an external folder to store configuration and other application data. Typically, you specify this folder via an environment variable or a property specified during deployment.
Related
I am currently working on a Java application in Intellij, and I cannot create a file within my artifact. As an example, I'm using File to create a file within the source, which is MainMenuData.txt.
File mainMenu = new File("MainMenuData.txt");
String absPath = mainMenu.getPath();
mainMenu.createNewFile();
BufferedReader br = new BufferedReader(new FileReader(absPath));
In this, I'm using File to make sure that file exists whenever it isn't.
Instead, I'd like to build within the (Production) artifact. Is that doable?
Anything helps. Thanks.
You could do that.
I assume your artifact is a jar file, which is nothing else than a zip file. You can obtain the location of your jar file in the file system and use the Zip File System to modify it. However I'm not sure, if the jvm might have a problem with that and it might not work on windows, since windows likes to block files, that are in use.
Also this would definitely fail, if your jar file is not stored locally.
A better approach would be to store your data files at the appropriate location in your system.
On Linux(and probably mac): <home>/.local/share/<your application name>/
On Linux(global): /var/lib/<application name>
On Windows(I think, better check it yourself): <appdata>/<your application name>
Your code would look something like this(for Linux):
File home = new File(System.getProperty("HOME");
File configDirectory = new File(home, ".local/share/<application name>");
configDirectory.mkdirs();
File mainMenu = new File(configDirectory, "MainMenuData.txt");
For windows do something similar. If you need both, you should check on which you are currently running.
I have a simple java web application with following folder structure.
When I deploy the web app it has data.json file in WEB-INF/classes folder. I need to write data to this file from controller.java class controller package which is in WEB-INF/classes folder.
I tried following code.
FileOutputStream output = new FileOutputStream("..\\data.json", true);
output.write(jsonObject.toJSONString().getBytes());
output.flush();
This doesn't give me any error which suggest that the operation happen in a file somewhere in my computer.
How can I write to the data.json file? I can't give absolute path here.
WEB-INF/classes is for the class-path. Files there should be considered read-only, cacheable resources (getResource, getResourceAsStream).
The HttpRequest.getServletContext().getRealPath("/WEB-INF") can be used,
for file system paths.
I suggest using the classes files as template, copied the first time to a real file system path, and then being overwritten.
Use /, not Windows \\.
Use close() and then flush() is not needed.
Use getBytes(StandardCharsets.UTF_8).
Following code worked,
FileOutputStream output = new FileOutputStream( request.getSession().getServletContext().getRealPath("WEB-INF/classes/data.json"), false);
I have created a java program that other testers will use to help with their testing. I will be sending them a zip file with the .jar, a readme.txt, and main.properties.txt file.
The main.properties.txt file is a template for the testers to input their DB access credentials. They will update the main.properties file with their db cred's and then attempt to run the .jar from the terminal or command line. The issue I am running into is this. My program needs this updated main.properties.txt file so it can create the connections to our DB's.
What instructions do I need to give in my readme so my program can successfully find the main.properties.txt? Does the main.properties need to be in the same directory as the .jar? Can the testers just create a file on their desktop or documents folders to put the .jar and main.props?
The other question I have is how do I pass this file to my program once its ran from the terminal? Currently it is really easy, because the main.props is part of my program and I can just do something like
Properties prop = new Properties();
FileInputStream in = new FileInputStream("src/main/resources/main.properties");
prop.load(in);
in.close();
But now main.properties is not part of the project anymore. I don't know how to change the code above so that it can find the text from a directory on the local. The location in which they wish to put their main.properties is out of my control so writing a static path will not work. Please help!
There are many ways, I'll show you two.
You need a File object that points to the main.properties file. Then you create a stream on this object new FileInputStream(File) , as you already did by using a String.
The problem of course is to get a relative path to main.properties.txt which works on all systems, regardless where the jar-File is located.
1. Desktop
In this case the main.properties.txt is located at the users desktop. Here is how you access it:
File desktop = new File(System.getProperty("user.home"), "Desktop");
File target = new File(desktop, "main.properties.txt");
Alernativly, if you plan to distribute configuration and property files that do not require user interaction, you may want to use locations like Temp or Documents (Windows).
2. Relative to the jar
Probably one of your best options. Assume the target is in the same folder than the jar-File (or at least in a fix structure relative to the jar). Here is how you access it (related question: how-to-get-the-path-of-a-running-jar-file):
CodeSource codeSource = YourMainClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
File jarDir = jarFile.getParentFile();
File target = new File(jarDir, "main.properties.txt");
well my directory structure is same eclipse based web application structure
through resourceAsStream() im able to read admin.properties file.
but i need to append this file too.
how to read this file
because
FileWriter fw = new FileWriter("/res/admin.properties");
will give FileNotFoundException . please inform me why its not visible to the servlet.
FileWriter writer = new FileWriter(getServletContext().getRealPath("admin.properties"));
This should work for you.Please keep in mind if you are testing from Tomcat in Eclipse, it will not change the file in your workspace rather it edits the one in wtpwebapps which is default location where your Eclipse Tomcat instance will deploy the application in default settings.
Assuming you are using Tomcat container.
I'm programming Java in Eclipse IDE. Here is code I want to read file:
File file = new File("file.txt");
reader = new BufferedReader(new FileReader(file));
I put file.txt in two place:
1) same folder of this SOURCE file.
2) in bin\...\ (same folder of this CLASS file)
But I allways receive NO FILE FOUND.
Please help me.
thanks :)
If the file ships with your application, it would be better accessed as a resource than as a file. Simply copy it to somewhere in your build path and use Class.getResourceAsStream or ClassLoader.getResourceAsStream. That way you'll also be able to access it if you bundle your app as a jar file.
Currently, you're looking for the file relative to the process's current working directory, which could be entirely unrelated to where the class files are.
if you put the file under sources and inside the package "test" for example, the path is:
./src/test/file.txt
you can use
File file = new File("./src/test/file.txt");
System.out.println(file.exists());
The path ./bin/test/file.txt will work in the second case and is more suitable for a normal java project