Java application to write CSS from local package - java

I am trying to programmatically build html pages that uses the same css. In order to do that I am creating necessary directories and a the css file.
As the picture below shows I have the css file in my package "resources" and I want to take it and write a local copy when I call the method writeCss
This is what the method looks like:
private void writeCss(){
try {
BufferedWriter out = new BufferedWriter(new FileWriter("new_project/css/style.css"));
//take the style.css from the package resources
//write the css to a local file
out.write("");
out.close();
} catch (IOException e) {}
}
I first thought just to copy and paste the entire CSS code into the out.write("") but the code is too long for the buffer.
Please suggest.

The easiest way would be:
Files.copy(Gui.class.getResourceAsStream("style.css"),
Paths.get("new_project", "css", "style.css"));

You may read the contents of the file using a classloader to help you finding the file, for example:
InputStream is = getClass().getResourceAsStream("/resources/style.css");
Please note that if the classloader is unable to find the file it will return null, but I think it will work just fine in your case. Normally you would read through the entire file using a buffer and then writing it straight to an output stream until the input stream gets consumed, no need for a writer if you wont modify or process the CSS file before writing it.

Related

How to remove ICEpdf temporary files after application has finished working?

I use ICEpdf library for PDF displaying at my desktop java application. Application adds annotations to PDF at runtime, but without changing original files — changes are displayed only during one 'session'. I recently discovered that application creates a lot of temporary files which consume quite a lot of disk space.
Method org.icepdf.core.pobjects.Document.setInputStream has the following code:
// Delete temp file on exit
tempFile.deleteOnExit();
So I suppose it has to remove temporary files after it used them, but it does not:
How can I programmatically remove all files created by application on exit or make standard file removing work?
To get temp folder path:
FileSystems.getDefault().getPath(System.getProperty("java.io.tmpdir"))
To remove files:
try (DirectoryStream<Path> paths = Files.newDirectoryStream(pathToDir, regex)){
paths.forEach(path -> path.toFile().delete());
} catch (IOException e) {
// handle io exception
}
where regex is filename pattern. In your case: "IcePdf*"

Casting multiform part to a file

I have a managed bean. An HTML/JSF page sends a zipped file as a Part. I need to extract the contents from it, but to do that I need it to be File. Is it possible to cast the Part to File like as follows, and then treat it like a normal zip file?
Part xmlFile;
public void myMethod()
{
File zippedFile = (File) getXmlFile();
....
}
If not, how would I go about doing so? I've looked on online but there seems to be very little information.
You can create a temporary file:
File aFile = File.createTempFile(PREFIX, SUFFIX);
And write the contents of your Part payload into that file:
try (InputStream input = part.getInputStream()) {
Files.copy(input, aFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
You may also want to make use of File's delete() or deleteOnExit() for cleaning up resources. Bear in mind that deleteOnExit() is only invoked when the JVM exits, which may not be what you want in your case.

How can I return the file path using the JNLP file chooser

Hi I am trying to get the returned file path by my JNLP file chooser. Here's my code.
I don't know how and where to get the file path. is it from fileContents? fileConents.getfilepath something like that?
try {
if (fileOpenService==null) {
fileOpenService = (FileOpenService)ServiceManager.
lookup("javax.jnlp.FileOpenService");
}
fileContents = fileOpenService.openFileDialog(path, xtns);
} catch(UnavailableServiceException use) {
use.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
Thanks in advance!
According to http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
You can call other methods on the File object, such as
getPath, isDirectory, or exists to obtain information about the file.
You can also call other methods such as delete and rename to change
the file in some way. Of course, you might also want to open or save
the file by using one of the reader or writer classes provided by the
Java platform. See Basic I/O for information about using readers and
writers to read and write data to the file system.
It is for security reasons that a FileContents will not return a path. The JRE asked the user if our app. could access the content of that file, not it's path.
It is a bit like the brower/HTML based file upload field. Some browsers provide the entire path, while more typically it is just the content/name.

how to access resources(Excel file) in jar file

Hi i have exported my java project as executable jar file. inside my project I am accessing a Excel file containing some data. Now I am not able to access the Excel file when I am trying to access the file.
My project structure is:
Java_Project_Folder
- src_Folder
- resources_Folder(Containing excel file)
I am accessing the excel file like
FileInputStream file=new FileInputStream(new File(System.getProperty("user.dir")
+File.separator+"resources"+File.separator+"Excel.xlsx"));
I have tried accessing this file using getResourceAsStream like:
FileInputStream file=(FileInputStream) this.getClass().getResourceAsStream
("/resources/Excel.xlsx");
But i am getting in is null exception. whats wrong can anyone help?
I bet you have no package called resources in your project.
Trying to use Class.#getResourceAsStream is the way to go. But this method does not return a FileInputStream. It returns an InputStream wich is an interface.
You should be passing the absolute name of the resource
InputStream is = getClass().getResourceAsStream("my/pack/age/Excel.xlsx");
where the excel file is located in the directory
resources/my/pack/age
The first step is to include the excel file itself in your project. You can create a resources folder like you show, but to make sure this gets included in your jar, you add the resources folder in along with your source code files so that it gets built into the jar.
Then
InputStream excelContent = this.getClass().getResourceAsStream("/resources/Excel.xlsx");
should work. From one post at least, the leading forward slash may also mess things up if you use the ClassLoader.
getClass().getResourceAsStream("/a/b/c.xml") ==> a/b/c.xml
getClass().getResourceAsStream("a/b/c.xml") ==> com/example/a/b/c.xml
getClass().getClassLoader().getResourceAsStream("a/b/c.xml") ==> a/b/c.xml
getClass().getClassLoader().getResourceAsStream("/a/b/c.xml") ==> Incorrect
ref: getResourceAsStream fails under new environment?
Also in eclipse you can set the resources folder as a source folder like this:
in the properties of your eclipse project, go to java build path, select sources, and check to see if all needed source fodlers are added (as source folders). If some are missing, just add them manually using add sources... button
ref: Java Resources Folder Error In Eclipse
I tried this and it is working for me.
My Test1 class is in default package, just check where your accessing class is in any package, if it is then go back to exact resource folder from classpath like this "../"
public class Test1 {
public static void main(String[] args) {
new Test1();
}
Test1(){
BufferedInputStream file= (BufferedInputStream) this.getClass().getResourceAsStream("resources/a.txt");
try {
System.out.println((char)file.read());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
FileInputStream file= (FileInputStream)
this.getClass().getResourceAsStream("/resources/Excel.xlsx");
Why do you need FileInputStream? Use
InputStream is = getClass().getResourceAsStream..
Secondly use "resources/Excel.xlsx"
Thirdly when constructing file like this
new
File(System.getProperty("user.dir")+File.separator+"resources"+File.separator+"Excel.xlsx"));
is hard to control slashes. use
new File("parent (userdir property)", "child (resources\Excel.xlsx)")

How to load a text file from a runnable jar

If i have a project which has a text file inside of it and i want to be able to read this text file which will be stored in my runnable jar then how can i do this? Currently i have a setup like this
public void someMethod()
{
File f = new File("aFileInEclipseResourcesFolder.txt");
doSomethingWithFile(f);
}
private void doSomethingWithFile(File f)
{
//print the data in the file;
}
The issue is the application cant locate the file if i use this approach but if i use a hard coded path to the file then it works. I know you can use getClass().getResourceAsStream() but this wont allow me to get the already written file in to a file object without rewriting it again, or is this assumption incorrect?
Regards
The getResourceAsStream delivers an InputStream you can use, just as a FileInputStream. You then can use:
InputStream is = getClass().getResourceAsStream("a/b/c/aFileInEclipseResourcesFolder.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); // Or "Cp1252"?
...
You don't want to use getResourceAsStream() you want
public URL getResource(String name)
the URL will give you the path to the resource and you can create a File object from that.
When I had this problem around a year ago the only solution I found was finding the location of the jar file (which is actually just a zip file), going through it and finding the file I wanted.
There are better methods around but they never worked for me (go figure), so keep this as a last resort.

Categories