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.
Related
I need some serious help with concepts. I have been given background context on the class, specifically this:
I just need to understand the purpose of this class? Can I create a text file (or any other type of file) with its constructors? Is this just for handling files, if so, what does that mean?
Any help whatsoever will be greatly appreciated!
Thank you
You could use the java.io.File to create a file on the file system:
File myFile = new File("myFile.txt");
myFile.createNewFile();
Note that invoking the constructor won't create the file on the file system. To create an empty file, the createNewFile() method has to be invoked.
The File simply represents a abstraction of the file location, not the file itself. It comes with operations on the file identified by the path: exists(), delete(), length(), etc.
What you probably want is to use the classes that allow you to write content to a file:
If you are to write text, you should use the Writer interface.
If you are to write binary content, you should use the OutputStream interface.
The classes FileWriter and FileOutputStream are, respectively, the ones that link the File and Writer/OutputStream concepts together. Those classes create the file on the file-system for you.
FileWriter myFileWriter = null;
File myFile = new File("myFile.txt");
try {
// file is created on the file-system here
myFileWriter = new FileWriter(myFile);
myFileWriter.write("hello");
} finally {
if (myFileWriter != null) {
myFileWriter.close();
}
}
You can create a file using the File.createNewFile method, or, if you are using Java 7 or newer, using the newer Files.createFile method.
The difference between the old File and the new Path classes is that the former mixed a reference to a path to a file on the filsystem and operations you can do on it, and the latter is just representing the path itself but allows you to query it and analyze its structure.
My app needs to get an existing file for processing. Now I have the path of the file in String format, how can I get the File with it? Is it correct to do this:
File fileToSave = new File(dirOfTheFile);
Here dirOfTheFile is the path of the file. If I implement it in this way, will I get the existing file or the system will create another file for me?
That's what you want to do. If the file exists you'll get it. Otherwise you'll create it. You can check whether the file exists by calling fileToSave.exists() on it and act appropriately if it does not.
The new keyword is creating a File object in code, not necessarily a new file on the device.
I would caution you to not use hardcoded paths if you are for dirOfFile. For example, if you're accessing external storage, call Environment.getExternalStorageDirectory() instead of hardcoding /sdcard.
The File object is just a reference to a file (a wrapper around the path of the file); creating a new File object does not actually create or read the file; to do that, use FileInputStream to read, FileOutputStream to write, or the various File helper methods (like exists(), createNewFile(), etc.) for example to actually perform operations on the path in question. Note that, as others have pointed out, you should use one of the utilities provided by the system to locate directories on the internal or external storage, depending on where you want your files.
try this..
File fileToSave = new File(dirOfTheFile);
if(fileToSave.exists())
{
// the file exists. use it
} else {
// create file here
}
if parent folder is not there you may have to call fileToSave.getParentFile().mkdirs() to create parent folders
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.
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.
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.