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 implementing a Branch Predictor for one of my classes and I am trying to read files from my src folder in Eclipse but for some reason it is not able to open the files. I have done this before with the exact same process so I'm not sure what is different.
traceFile is set from the command line and if I print "input", it will print out the correct file path and I have confirmed it is there manually.
ClassLoader loader = BiModalPredictor.class.getClassLoader();
File input = new File(loader.getResource(traceFile).getFile());
Scanner fin = new Scanner(input);
Is there any insight as to why this might be happening? I've tried restarting Eclipse, refreshing the files, and I've also tested it on another program which worked. No idea why it can't find this file.
Resources on the classpath, i.e. available through the classloaders getResource method, will not be files on the file system when your application is deployed as a jar file, or deployed in general. Do not use File with such resources, instead use getResourceAsStream to access the resource content.
Besides, your code is wrong. getResource() returns a URL. If you want a File object from a URL, you should use new File(uri), where the URI is obtained by calling url.toURI().
File input = new File(loader.getResource(traceFile).toURI());
I am trying to generate a XML file and save it in /WEB-INF/pages/.
Below is my code which uses a relative path:
File folder = new File("src/main/webapp/WEB-INF/pages/");
StreamResult result = new StreamResult(new File(folder, fileName));
It's working fine when running as an application on my local machine (C:\Users\userName\Desktop\Source\MyProject\src\main\webapp\WEB-INF\pages\myFile.xml).
But when deploying and running on server machine, it throws the below exception:
javax.xml.transform.TransformerException:
java.io.FileNotFoundException
C:\project\eclipse-jee-luna-R-win32-x86_64\eclipse\src\main\webapp\WEB INF\pages\myFile.xml
I tried getServletContext().getRealPath() as well, but it's returning null on my server. Can someone help?
Never use relative local disk file system paths in a Java EE web application such as new File("filename.xml"). For an in depth explanation, see also getResourceAsStream() vs FileInputStream.
Never use getRealPath() with the purpose to obtain a location to write files. For an in depth explanation, see also What does servletcontext.getRealPath("/") mean and when should I use it.
Never write files to deploy folder anyway. For an in depth explanation, see also Recommended way to save uploaded files in a servlet application.
Always write them to an external folder on a predefined absolute path.
Either hardcoded:
File folder = new File("/absolute/path/to/web/files");
File result = new File(folder, "filename.xml");
// ...
Or configured in one of many ways:
File folder = new File(System.getProperty("xml.location"));
File result = new File(folder, "filename.xml");
// ...
Or making use of container-managed temp folder:
File folder = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
File result = new File(folder, "filename.xml");
// ...
Or making use of OS-managed temp folder:
File result = File.createTempFile("filename-", ".xml");
// ...
The alternative is to use a (embedded) database or a CDN host (e.g. S3).
See also:
Recommended way to save uploaded files in a servlet application
Where to place and how to read configuration resource files in servlet based application?
Simple ways to keep data on redeployment of Java EE 7 web application
Store PDF for a limited time on app server and make it available for download
What does servletcontext.getRealPath("/") mean and when should I use it
getResourceAsStream() vs FileInputStream
just use
File relpath = new File(".\pages\");
as application cursor in default stay into web-inf folder.
If I do this
fis = new FileInputStream(new File(".").getAbsolutePath() + "/sudoinput.txt");
Its trying to write to this location on the server. I am not sure if this is a writable
place.
FILE NAME (fos)::::::::::::::::::/opt/tomcat/temp/./sudoinput.txt
FILE NAME (fis)::::::::::::::::::/opt/tomcat/temp/./sudoinput.txt
I wanted to write to
webapps/sudoku/WEB-INF/classes
which is basically
C:\Users...\git\sudo-project\sudo\src\main\resources
On Eclipse Windows 7 I get this
error
src\main\resources\sudoinput.txt (The system cannot find the path specified)
if I give
fis = new FileInputStream("src/main/resources/sudoinput.txt");
I have tried this too:
fis = new FileInputStream("src\\main\\resources\\sudoinput.txt");
but doesn't work.
how should I create a fileinputstream to be able to write to src/main/resources ?
please note that I am using eclipse windows to do dev and will be uploading the .war file on to a unix server if this changes the way in which the paths need to be specified.
The src/main/resources folder is a folder that is supposed to contain resources for your application. As you noted, maven packages these files to the root of your file so that you can access them in your library.
Have a look at the Maven documentation about the standard directory layout.
In certain cases, it is possible to write to the context but it is not a good idea to try it. Depending on how your webapp is deployed, you might not be able to write into the directory. Consider the case when you deploy a .war archive. This would mean that you try to write into the war archive and this won't be possible.
A better idea would be to use a temporary file. In that way you can be sure this will work, regardless of the way your web application is deployed.
Agree with Sandiip Patil. If you didn't have folder inside your resources then path will be /sudoinput.txt or in folder /folder_name/sudoinput.txt. For getting file from resources you should use YourClass.class.getResource("/filename.txt");
For example
Scanner scanner = new Scanner(TestStats.class.getResourceAsStream("/123.txt"));
or
Scanner scanner = new Scanner(new `FileInputStream(TestStats.class.getResource("/123.txt").getPath()));`
Also look at: this
You can keep the file created under resources and call .class.getresource(your_file_name_or_path_separated_with_forward_slash);
See if it works for you.
If you like to create files in webapps/sudoku/WEB-INF/classes which is in the end within the created WAR file which can be achieved by putting the files you want into src/main/resources/
This means in other words you need to create the folder src/main/resources and put the files you like into this directory.
I have an application that creates a temporary mp3-file and puts it in a directory like C:\
File tempfile = File.createTempFile("something", ".mp3", new File("C:\\));
I'm able to read it by just using that same tempfile again.
Everything works fine in the Eclipse IDE.
But when I export my project for as a Runnable jar, my files are still being made correctly (I can play them with some normal music player like iTunes) but I can't seem to read them anymore in my application.
I found out that I need to use something like getClass().getResource("/relative/path/in/jar.mp3") for using resource files that are in the jar. But this doesn't seem to work if I want to select a file from a certain location in my file system like C:\something.mp3
Can somebody help me on this one?
It seems you dont have file name of the temp files . When you was running your program in eclipse that instance was creating a processing files, but after you made a runable you are not able to read those file that instance in eclipse created, You runable file can create its own temp file and can process them,
To make temp files globe put there (path + name ) entries in some db or property file
For example of you will create a temp file from the blow code
File tempfile = File.createTempFile("out", ".txt", new File("D:\\"));
FileWriter fstream = new FileWriter(tempfile);//write in file
out = new BufferedWriter(fstream);
the out will not be out.txt file it will be
out6654748541383250156.txt // it mean a randum number will be append with file
and you code in runable jar is no able to find these temp files
getClass().getResource() only reads resources that are on your classpath. The path that is passed to getResource() is, in fact, a path relative to any paths on your current classpath. This sounds a bit confusing, so I'll give an example:
If your classpath includes a directory C:\development\resources, you would be able to load any file under this directory using getResource(). For example, there is a file C:\development\resources\mp3\song.mp3. You could load this file by calling
getClass().getResource("mp3/song.mp3");
Bottom line: if you want to read files using getResource(), you will need those files to be on your classpath.
For loading from both privileged JARs and the file system, I have had to use two different mechanisms:
getClass().getClassLoader().getResource(path), and if that returns null,
new File(path).toURI().toURL();
You could turn this into a ResourceResolver strategy that uses the classpath method and one or more file methods (perhaps using different base paths).
InputStream inp = new FileInputStream("src/main/resources/ExportHour.xls");
I have a file in the src/main/resources folder of my Java Spring project.
I am attempting to create an inputstream in one of my Controllers, however I always get a file not found exception. When I change the path location to point specifically to the file on my machine, it works fine.
Any way I can make it so the file can be found within the java project?
Try with spring ClassPathResource.
InputStream inp = new ClassPathResource("ExportHour.xls").getInputStream();
That is because the resources folder in maven is put in your jar file directly i.e. the ExportHours.xls file is put inside your jar in the root directory.
It sounds like you could just change the working directory of your process - it's not where you think it is, I suspect. For example, I suggest you write
File file = new File("src/main/resources/ExportHour.xls");
and then log file.getAbsolutePath(), to see what exact file it's using.
However, you should almost certainly not be using a FileInputStream anyway. It would be better to use something like:
InputStream inp = Foo.class.getResourceAsStream("/ExportHour.xls");
... for some class Foo which has a classloader which includes the resources you need.
(Or possibly /resources/ExportHour.xls", depending on your build structure.)
That way even when you've built all of this into a jar file, you'll still be able to open the resource.