I have to write a Java 8 Swing app and a part of the application generates an output file (Excel spreadsheet). So at some point in the UI, the user will have to:
Select a directory on their file system, where the Excel file will be written to; and then
Enter the name of the Excel file (if they specify ".xls" or ".xlsx" in the file name, the app will output/write the file in the respective XLS/XLSX output; if they omit the file extension the default will be XLSX)
I'm interested in what a decent UX solution here is, and how that maps to Swing controls and their layout.
I know I can use JFileChooser to choose a directory or a specific file, but I've never used it to select a directory and enter the name of a new (doesn't exist on the file system yet) file name + extension.
Any ideas as to what solution I can offer here that is functional, elegant and simple/easy to use & understand?
You can use Apache's FileNameUtils, or implement you own extension extraction with String manipulation using substring and indexOf... I'll give you an example of first case.
After using a default JFileChooser as suggested, you can just check for specified file name, as JFileChooser will return a File object (or null if nothing is selected, so first check for null values):
JFileChooser fileChooser = new JFileChooser();
File selectedFile = fileChooser.getSelectedFile();
if (selectedFile != null) {
String givenExtension = FilenameUtils.getExtension(selectedFile.getName());
boolean noExtension = "".equals(givenExtension);
boolean xlsx = givenExtension.toLowerCase().contains("xlsx");
boolean xls = givenExtension.toLowerCase().contains("xls");
String newFileName = selectedFile.getName();
if (noExtension) {
newFileName += ".xlsx";
} else if (!xlsx && !xls) {
throw new Exception("Invalid name");
}
}
Remove toLowerCase() if you don't want different cases to be accepted.
This should do what you want ;)
Related
I'm trying to set a JFileChooser to only allow choosing a specific file type (pdf) via the showOpenDialog.
I've set a File Filter but I'm confused as to what action on the JFileChooser it has.
What I'm trying to achieve is:
Visually exclude other file types to prevent the user from choosing them from the list.
Actually prevent selection of other types or an invalid file. (i.e. have the getSelectedFile() to actually return a valid pdf file)
Here is my code:
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setAcceptAllFileFilterUsed(false);
fc.setFileFilter(new FileNameExtensionFilter("PDF Files", "pdf"));
fc.setDialogTitle("Load MSDS");
int op = fc.showOpenDialog(this);
if(op == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
lbl_msds_loaded.setForeground(Color.BLACK);
lbl_msds_loaded.setText(f.getName() + " (Size: " + utils.FileUtils.getFileSizeMegaBytes(f, 3) + ")");
}
I get this behavior:
Visually - The filtering works and the dialog does only show PDF Files, therefore I can only choose pdf files from the list.
But - I'm still able to manually select an invalid file, by typing in some name in the 'File name:' field and click open (or hit enter).
For example: if I write Untitled.png (which does exist in the currently opened directory) and open, I will get that png file loaded.
Or if write a file name that doesn't exist and click open, I will actually get a new file with that name loaded.
(By loaded I mean the file that getSelectedFile() will return).
Is there a way to not allow the dialog approve the open action if an invalid file is set (based on the filter ofcourse)?
Shouldn't this already be the case when using JFileChooser Dialogs with filters?
What exactly is the filter doing here? The documentation for JFileChooser does not explain any of these aspects.
I would really appreciate an explanation on how this works.
Also what is the difference between setFileFilter and addChoosableFileFilter? They give the exact same behavior.
Finally here's a few screenshots of the Dialog and the JFrame form I'm working on for some context:
https://ibb.co/bFVqVmt
https://ibb.co/5BcsXSW
https://ibb.co/2qq0qr9
https://ibb.co/jMXXXyN
https://ibb.co/g3kvtfd
https://ibb.co/2FshJpt
Thanks alot!
my folder name is coming in below format
yyyyMMdd_HHmmss
my output is
20180828_021335
20180828_021330
20170828_011330
20180828_1211330
how do i create regex to find latest folder name(latest folder created) in java
i had written below code but it displays folder name based on lastModified but i wish to get folder name based on folder name which is coming yyyyMMdd_HHmmss format. i want regex to search latest folder based on folder name
String getLatestFolderPath(String path) {
File dir = new File(path);
File max = null;
for (File file : dir.listFiles()) {
if (file.isDirectory()
&& (max == null || max.lastModified() < file.lastModified())) {
max = file;
}
}
return max.toString();
}
I suggest:
public static Optional<String> getLatestFolderPath(String dirPathName) throws IOException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMdd_HHmmss");
Path dirPath = Paths.get(dirPathName);
Optional<Path> op = Files.list(dirPath)
.filter(Files::isDirectory)
.max(Comparator.comparing(p
-> LocalDateTime.parse(p.getFileName().toString(), formatter)));
return op.map(Path::toString);
}
IMHO a regular expression has no place in your task. Instead I am parsing the date and time in the file name into a LocalDateTime and picking the latest. This also gives a validation of your file names. In fact, since the last one of your example directories has a digit too many, it will cause a java.time.format.DateTimeParseException: Text '20180828_1211330' could not be parsed, unparsed text found at index 15.
I am using some modern stuff like the modern file API, the stream API and an Optional. You don’t need these to implement the basic idea, I just preferred to write the code this way. If you need help filtering out what you want from what you don’t want, please follow up in a comment.
I am doing a project for vehicle repair center. In this project I need to upload photos of the damaged vehicle so employees can watch them later.
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filePath = f.getAbsolutePath();
path.setText(filePath);
File imgFile = new File(filePath);
try {
FileInputStream fin = new FileInputStream(imgFile);
I tried above, but I can choose only one photo at one time, like this:
I need these kind of thin
ddddd
i don't do java but a quick glance at the manual suggests you need to enable selection of multiple files:
setMultiSelectionEnabled
public void setMultiSelectionEnabled(boolean b)
Sets the file chooser to allow multiple file selections.
Parameters:
b - true if multiple files may be selected
See Also:
isMultiSelectionEnabled()
https://docs.oracle.com/javase/8/docs/api/javax/swing/JFileChooser.html#setMultiSelectionEnabled-boolean-
I am working on a web application in which it takes action log for every minute i.e.., any action performed will be appended into a text file with current date as its name and if no action performed then it will append current time stamp in that same file. So for everyday one new file will be created and action performed will be appended in that file for that whole day. What I want now is, all those files are present in D:\ -->(presentdate)<--.txt and when I give a particular date in the same format as that of file name in the "text field" and click on submit in my web application it has to show that file present in D drive as a hyper link(if present in the drive) and when I click on the hyperlink it should simply show the content in that file. I want to know how to search for a file in particular folder/drive without mentioning file name directly but searching for files which are having file names in specific format(Example: 27_06_2014.txt).Any suggestions will be very helpful.
Thank you.
String path = "D:" + File.pathSeparator + fileSearched + ".txt";
File f = new File(path);
if(f.exists()) {
//do your stuff
}
//I dont know why would you like to search them as a list but anyways
File dir = new File("D:");
dir.mkdir();
for(String s : dir.list()){
if(s.equalsIgnoreCase(fileSearched)){
//do your stuff
}
}
Here's the documentation for the java.io.File class
I am stuck with an issue with reading .xlsx file. Some temporary files with random name are created under /tmp/poifiles directory whenever I use WorkbookFactory.create(inputStream);. This directory is created with RW-R-R- permission for the first user. So another user on the same machine when tries to access these files, he CANNOT.
Please suggest me any way
1) How can I create these temp files under /tmp directory and not always in /tmp/poifiles (I am using RHEL V5.0)
2) and how can I configure POI such as to change the location from where it reads the temporary files??
Anymore help to solve my problem of different users accessing same .xlsx files through POI is badly needed.
Yuppie...I got the solution....
POI uses the following method to create temp files.
public static File createTempFile(String prefix, String suffix)
{
if (dir == null) {
dir = new File(System.getProperty("java.io.tmpdir"), "poifiles");
dir.mkdir();
if (System.getProperty("poi.keep.tmp.files") == null) {
dir.deleteOnExit();
}
}
File newFile = new File(dir, prefix + rnd.nextInt() + suffix);
if (System.getProperty("poi.keep.tmp.files") == null) {
newFile.deleteOnExit();
}
return newFile;
}
Now here as we can see it gets the location from property "java.io.tmpdir" and creates poifiles directory inside that...
I changed the location of java.io.tmpdir by setting this property (using System.setProperty("java.io.tmpdir", "somepath"))to user specific location..and Voila....Every user now can create temp files at location always accessible to them and not only the first user gets the privilege to create directory accessible only to him ...!!!
Here is how you can change the location from where POI reads the temporary files programmatically if you are not able to change system property "java.io.tmpdir"
File dir = new File("somepath");
dir.mkdir();
TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy(dir));
This is driven by the Apache POI TempFile and DefaultTempFileCreationStrategy helper classes.