I have no problem opening multiple file types, however I want the option to be able to save multiple file types. I can't figure out how to get the option the user selected to save their file types as.
Here is my code:
//.txt and .encm files are allowed
final JFileChooser txtOrEncmChooser = new JFileChooser(new File(System.getProperty("user.dir")));
//only allow user to use .txt and .encm files
txtOrEncmChooser.addChoosableFileFilter(new FileNameExtensionFilter("Encrypted Data File (*.encm)", "encm"));
txtOrEncmChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text File (*.txt)", "txt"));
txtOrEncmChooser.setAcceptAllFileFilterUsed(false);
//displays save file dialog
int returnVal = txtOrEncmChooser.showSaveDialog(FileEncryptionFilter.this);
//use chose to save file
if (returnVal == JFileChooser.APPROVE_OPTION)
{
//selects file
File fileName = txtOrEncmChooser.getSelectedFile();
/****The problem is here, how do I figure out what file type the user selected?****/
if .txt is selected{
String filePath = fileName.getPath() + ".txt"; //file path
}
else if .encm is selected
{
String filePath = fileName.getPath() + ".encm"; //file path
}
}
I have searched the forums for solutions, but I only found the solution for opening multiple file types, not saving multiple file types.
https://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html#getFileFilter()
FileNameExtensionFilter f = (FileNameExtensionFilter) txtOrEncmChooser.getFileFilter();
Since getExtensions() returns an array, you'll have to iterate through all the extensions. If you are sure that it only contains one element, of course, you won't need to do this. Just check f.getExtensions()[0].equals("txt"), for example. You could also create your file filters as local variables and then compare them with the selected one.
Related
I want to upload files and save them into specific directory.And i am new to files concept.When i uploading files from my page they are saved in another directory(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) and not in specified directory.I am unable to set it.Please help me in finding a solution.For all help thanks in advance.
public static Result uploadHoFormsByHeadOffice() throws Exception {
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() -->> ");
final String basePath = System.getenv("INVOICE_HOME");
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData(); // get Form Body
StringBuffer fileNameString = new StringBuffer(); // to save file path
// in DB
String formType = body.asFormUrlEncoded().get("formType")[0];// get formType from select Box
FilePart upFile = body.getFile("hoFiles");//get the file details
String fileName = upFile.getFilename();//get the file name
String contentType = upFile.getContentType();
File file = upFile.getFile();
//fileName = StringUtils.substringAfterLast(fileName, ".");
// path to Upload Files
File ftemp= new File(basePath +"HeadOfficeForms\\"+formType+"");
//File ftemp = new File(basePath + "//HeadOfficeForms//" + formType);
File f1 = new File(ftemp.getAbsolutePath());// play
ftemp.mkdirs();
file.setWritable(true);
file.setReadable(true);
f1.setWritable(true);
f1.setReadable(true);
//HoForm.create(fileName, new Date(), formType);
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() <<-- Redirecting to Upload Page for Head Office");
return redirect(routes.HoForms.showHoFormUploadPage());
}
}
I really confused why the uploaded file is saved in this(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) path.
You're almost there.
File file = upFile.getFile(); is the temporary File you're getting through the form input. All you've got to do is move this file to your desired location by doing something like this: file.renameTo(ftemp).
Your problem in your code is that you're creating a bunch of files in memory ftemp and f1, but you never do anything with them (like writing them to the disk).
Also, I recommend you to clean up your code. A lot of it does nothing (aforementioned f1, also the block where you're doing the setWritable's). This will make debugging a lot easier.
I believe when the file is uploaded, it is stored in the system temporary folder as the name you've provided. It's up to you to copy that file to a name and location that you prefer. In your code you are creating the File object f1 which appears to be the location you want the file to end up in.
You need to do a file copy to copy the file from the temporary folder to the folder you want. Probably the easiest way is using the apache commons FileUtils class.
File fileDest = new File(f1, "myDestFileName.txt");
try {
FileUtils.copyFile(ftemp, fileDest);
}
catch(Exception ex) {
...
}
I am exploring Jfilechooser.I already get the file path in the Jfilechooser.Now I want to display the information like file name, file size, location, and access rights.Is their anyway to display those information using the file path only.Anyone can help me?I want it to display in a TextArea.
this is the how I pop up a Jfilechooser.
private void browsebuttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
fieldlocation.setText(filename);
}
Take a look at the JavaDoc for File:
File.getName()
Will return the name of the file
File.length()
Will return the size of the file in bytes
File.getAbsolutePath()
Will return the absolute path of the file
File.canRead()
File.canWrite()
File.canExecute()
Will return your access rights on the file.
One thing I would note about your code is that you don't check the return value from the file chooser. If the user clicks cancel you probably want to abort processing. The way to do this is to check the return value of JFileChoose.showOpenDialog(null); like so:
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
Straight from the JavaDoc.
In short I would suggest that you (re)?read the documentation for the APIs you are using. It will save you much time in the long run if you understand your own code.
I need to check whether or not a file exists. Which can be accomplished by File#exists() method. But this existence checking is case sensitive. I mean if I have a file name some_image_file.jpg in code but if physically the file is some_image_file.JPG then this method says that the file doesn't exists. How can I check the file existence with case insensitivity to the extension and get the actual file name?
In my scenario, I have a excel file. Each row contains metadata for files and the filename. In some cases I have only the filename or other cases I can have full path. I am denoting a row as a document.
These files are placed in the server. My job is to
Read the excel file row by row and list all the documents.
Take out the filename or filepath.
Create the full path of the file.
Check if the file exists or not.
Validate other metadata/information provided in the document.
Upload the file.
My application throws exception in case the file doesn't exists or if some metadata are invalid.
The excel file is written by the customer and they wrote some file name wrong, I mean if the file physically have the extension in lower case, they have written the extension in upper case, also the converse is true.
I am running the application in unix server.
As the file extensions are not matching so the File#exists() is giving false and eventually my code is throwing exception.
The folders where the files are placed can have 30000 or more files.
What I want is
To take the full path of the file.
Check if the file exists or not.
If it does not exists then
Check the file existence by converting the case of the extension.
If it doesn't exist after the case conversion then throw exception.
If it exists, then return the actual file name or file path.
If the file name has file extension something like .Jpg, don't know what to do! Should I check it by permuting it by changing the case?
You could get the file names in a folder with
File.list()
and check names by means of
equalsIgnoreCase()
Or try http://commons.apache.org/io/
and use
FileNameUtils.directoryContains(final String canonicalParent, final String canonicalChild)
This way I had solved the problem:
public String getActualFilePath() {
File givenFile = new File(filePath);
File directory = givenFile.getParentFile();
if(directory == null || !directory.isDirectory()) {
return filePath;
}
File[] files = directory.listFiles();
Map<String, String> fileMap = new HashMap<String, String>();
for(File file : files) {
if(file.isDirectory()){
continue;
}
String absolutePath = file.getAbsolutePath();
fileMap.put(absolutePath, StringUtils.upperCase(absolutePath));
}
int noOfOcc = 0;
String actualFilePath = "";
for(Entry<String, String> entry : fileMap.entrySet()) {
if(filePath.toUpperCase().equals(entry.getValue())) {
actualFilePath = entry.getKey();
noOfOcc++;
}
}
if(noOfOcc == 1) {
return actualFilePath;
}
return filePath;
}
Here filePath is the full path to the file.
The canonical name returns the name with case sensitive. If it returns a different string than the name of the file you are looking for, the file exists with a different case.
So, test if the file exists or if its canonical name is different
public static boolean fileExistsCaseInsensitive(String path) {
try {
File file = new File(path);
return file.exists() || !file.getCanonicalFile().getName().equals(file.getName());
} catch (IOException e) {
return false;
}
}
I want to create a new file while file type is choosing by the user on JFileChooser. How this is possible. I use this code for JFileChooser:
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Save data in your file format");
FileFilter type1 = new ExtensionFilter("Access 2007 Database(*.accdb)", ".accdb");
FileFilter type2 = new ExtensionFilter("Access 2002-2003 Database(*.mdb)", ".mdb");
chooser.addChoosableFileFilter(type1);
chooser.addChoosableFileFilter(type2);
int actionDialog = chooser.showSaveDialog(frame);
Now I an able to get the "File Name" when the user select any file by this code:
chooser.getSelectedFile().getName();
But I dont know how to get "Files of type" when user select any file.
For the convenience I also attach photo of JFileChooser:
You can get that information using JFileChooser .getFileFilter()
From the Javadocs:
Returns the currently selected file filter
I'm using this bit of code:
fileBrowser() {
String toReturn = null;
JFileChooser Chooser = new JFileChooser();
int choosen = Chooser.showOpenDialog(fileBrowser.this);
if (choosen == JFileChooser.APPROVE_OPTION) {
System.out.println(Chooser.getCurrentDirectory().toString()+"\\"+Chooser.getSelectedFile().getName());
}
}
To get the selected file name and location, which is all working fine. I was wondering as an addition, is there also a way to get all the filenames in that directory as well? something like .getAllFiles() I've had a search around and can't find one?
Thanks in Advance.
Sure, use
File[] filesInDirectory = chooser.getCurrentDirectory().listFiles();
Then you can iterate over that array:
for ( File file : filesInDirectory ) {
System.out.println(file.getName());
}
Well, there's File.list(). This will list all files by their name from the specified directory (i.e. File). But this will also return directory names. In order to circumvent that, use the other File.list(FilenameFilter filter) method that will enable you to filter out directories from the listing.