I cant get jfilechooser to show the files I return from FileNameFilter. It still shows me all the files inside the folder. I believe fileChooser.setSelectedFiles(listOfMatchingFiles); should set what contents are displayed. I've searched the net but have only found examples of how to set what type of file extensions are viewable. Any help is appreciated. Thanks
final String[] currSelection = selecName.split("_");
FilenameFilter fileNames = new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.startsWith(currSelection[0])) {
return true;
} else {
return false;
}
}
};
JFileChooser fileChooser = new JFileChooser();
File[] listOfMatchingFiles = fileLOcation.listFiles(fileNames);
fileChooser.setCurrentDirectory(fileLOcation);
fileChooser.setSelectedFiles(listOfMatchingFiles);
for (File a : listOfMatchingFiles) {
//displays the set of files according to currSelection[0]
System.out.println(a);
}
fileChooser.setDialogTitle(currSelection[0]);
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File fileToVIEW = fileChooser.getSelectedFile();
}
Related
I want to filter files stored in my phone with the .apk extension. I have tried the below code but it filters files found only in sdcard/file.apk
but I want it to filter the file by searching into the sub directories of sdcard also.
For example if there is an apk file inside sdcard/download/mm.apk it should filter it and also if there is another file in sdcard/New Folder/ABC/cc.apk it should filter it too.
How can I do that? thank you for your help...
ExtFilter apkFilter = new ExtFilter("apk");
File file[] =Environment.getExternalStorageDirectory().listFiles(apkFilter);
Log.i("InstallApk","Filter applied. Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
Log.i("InstallApk",
"FileName:" + file[i].getName());
}
ArrayAdapter af=new ArrayAdapter<File>(this,android.R.layout.simple_list_item_1,android.R.id.text1,file);
ListView ll=(ListView) findViewById(R.id.mainListView1);
ll.setAdapter(af);
}
class ExtFilter implements
FilenameFilter {
String ext;
public ExtFilter(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name)
{
return name.endsWith(ext);
}
}
You have to do it recursively. It is not enough to check for the extension, you must also verify that it is a regular file cos I can as well name a directory dir.apk. Verifying that it is a regular file is also not enough since one can name any file with any extension. Regardless, checking that it is a regular file should be enough without consideration of the intended action on these files.
public void someFunction() {
List<File> apkFiles = getApkFiles(Environment.getExternalStorageDirectory(), new ApkSearchFilter());
File file[] = apkFiles.toArray(new File[apkFiles.size()]);
Log.i("InstallApk", "Filter app\"lied. Size: " + file.length);
for (File aFile : file) {
Log.i("InstallApk", "FileName:" + aFile.getName());
}
}
List<File> getApkFiles(File file, ApkSearchFilter filter) {
if (filter.isApk(file))
return Collections.singletonList(file);
else if (filter.isDirectory(file)) {
LinkedList<File> files = new LinkedList<>();
for (File subFile : file.listFiles()) {
files.addAll(getApkFiles(subFile, filter));
}
return files;
} else return Collections.emptyList();
}
class ApkSearchFilter implements FileFilter {
boolean isApk(File file) {
return !file.isDirectory() && file.getName().matches(".*\\.apk");
}
boolean isDirectory(File file) {
return file.isDirectory();
}
#Override
public boolean accept(File file) {
return isDirectory(file) || isApk(file);
}
}
This is one in many way you can try, don't forget to add permission in manifest:
private List<String> ReadSDCard()
{
File f = new File("your path"); // Environment.getExternalStorageDirectory()
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
String filePath = file.getPath();
if(filePath.endsWith(".apk"))
tFileList.add(filePath);
}
return tFileList;
}
Can anyone help me to skip file having extension "read" in my code ?
I have two files in my folder:
123.csv
123.csv.read
After execution every csv file is converted into ".csv.read", but if the same file comes again, that file should be skipped.
Like this file (123.csv.read) has been processed already, so if same new file(123.csv) comes, I want to be skipped that file.
In my code below, after 123.csv file is processed, the folder has only one file 123.csv.read. break is not behaving as I was expecting.
context.Str = ((String)globalMap.get("tFileList_1_CURRENT_FILEPATH"));
String extension = context.Str.substring(context.Str.lastIndexOf(".") + 1);
if (extension.equals("read"))
{
break;
}
else {
System.out.println("Good File to Process");
}
public static void listFile(final String folder, final String ext) {
ExtFilter filter = new ExtFilter(ext);
File dir = new File(folder);
if (dir.isDirectory() == false) {
System.out.println("Directory does not exists : " + FindFileExtension.FILE_DIR);
return;
}
// list out all the file name and filter by the extension
String[] list = dir.list(filter);
if (list.length == 0) {
System.out.println("no files end with : " + ext);
return;
}
for (String file : list) {
String temp = new StringBuffer(FindFileExtension.FILE_DIR).append(File.separator).append(file).toString();
System.out.println("file : " + temp);
// do your stuff here this file is not processed
}
}
public static class ExtFilter implements FilenameFilter {
private String ext;
public ExtFilter(final String ext) {
this.ext = ext;
}
public boolean accept(final File dir, final String name) {
return (name.endsWith(this.ext));
}
}
You can do something like that,it might help you
You can try this:
For example 123.csv file came again, then you check this if exist in read folder
if(!new File(123.csv+".read").exist()) {
// if this file is not exist, then it means that this has not been processed
// process the file
} else {
// do some other staff
}
Edit: Or you can try this
public static void main(String[] args) throws Exception {
File dir = new File("your_path");
File[] processedFiles = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().contains("read");
}
});
List<File> files = Arrays.asList(processedFiles);
File[] noneProcessedFiles = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return !pathname.getName().contains("read");
}
});
for (File file : noneProcessedFiles) {
if (!files.stream().findAny().get().getName().contains(file.getName())) {
// process the file....
System.out.println("Not found ... " + file.getName());
} else {
// do some other staff....
System.out.println("Fount the file");
}
}
}
I am trying to create a FileFilter that will only allow the user to open a directory that contains a certain file. The use case is that these directories are workspaces that have a file called smart.workspace inside.
Currently my filter is as follows...
class SMARTWorkspaceFilter extends javax.swing.filechooser.FileFilter {
String description = "SMART Workspace";
String fileNameFilter = "smart.workspace";
SMARTWorkspaceFilter() {
}
#Override
public boolean accept(File file) {
log.debug("Testing file: " + file.getName());
if (file.isFile()) {
return false;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
log.debug("Directory: " + f.isDirectory());
log.debug("Name: " + f.getName());
if (f.isDirectory()) {
return true;
}
if (f.getName().equals(fileNameFilter)) {
return true;
}
}
}
return false;
}
#Override
public String getDescription() {
return description;
}
}
Obviously my problem is that to allow the user to navigate to the workspace folder I have to allow for sub directories.
For the file chooser I am using the option DIRECTORIES_ONLY.
Is it possible to only allow the user to select a directory based on the directories contents?
For example the directory 'workspace' exists at C://Folder1/Folder2/wokspace, I would want to allow the FileChooser to 'start' at C:// and allow the user to navigate to the 'workspace' folder and accept it. The FileChooser shouldn't allow the acceptance of Folder1 or Folder2 but still allow the navigation through Folder1 and Folder2.
I dont think you can make the FileFilter differentiate between "files/directories that should be displayed an can be accessed" and "files/directories that can be selected".
A solution for your problem that comes to my mind is: Let the user search/select the smart.workspace file and then navigate from there to the parent folder.
If you need the dialog to do exactly as you described above you will have to get involved in detail with the JFileChooser. Hopefully extending that class gives you enough access to change the behaviour as desired.
Your problem is that your return statements are conflicting. You don't need the first if statement as you're returning false by default (unless it's a directory AND that directory contains the special file).
class SMARTWorkspaceFilter extends javax.swing.filechooser.FileFilter {
String description = "SMART Workspace";
String fileNameFilter = "smart.workspace";
SMARTWorkspaceFilter() {
}
#Override
public boolean accept(File file) {
log.debug("Testing file: " + file.getName());
// have we selected a directory
if(file.isDirectory()) {
File[] files = file.listFiles();
// for all files in the directory
for(File f : files) {
log.debug("Directory: " + f.isDirectory());
log.debug("Name: " + f.getName());
// if the name is the name of the special file, return true
if(f.getName().equals(fileNameFilter)) {
return true;
}
}
}
// else, return false
return false;
}
#Override
public String getDescription() {
return description;
}
}
Ultimately #SebastianH is correct, it doesn't seem possible through the FileFilter. instead I extended the JFileChooser.
javax.swing.JFileChooser fileChooser = new javax.swing.JFileChooser(defaultLocation){
#Override
public boolean isDirectorySelectionEnabled() {
setOpenButtonState(this, false);
File file = getSelectedFile();
if(file == null){
return false;
}
if(file.isDirectory()){
File[] files = file.listFiles();
for(File f : files){
if(f.isFile() && f.getName().equals("smart.workspace")){
setOpenButtonState(this, true);
return true;
}
}
}
return false;
}
private void setOpenButtonState(java.awt.Container c, boolean flag) {
int len = c.getComponentCount();
for (int i = 0; i < len; i++) {
java.awt.Component comp = c.getComponent(i);
if (comp instanceof javax.swing.JButton) {
javax.swing.JButton b = (javax.swing.JButton)comp;
if ( b != null && b.getText() != null && b.getText().equals("Open") ) {
b.setEnabled(flag);
}
} else if (comp instanceof java.awt.Container) {
setOpenButtonState((java.awt.Container) comp, flag);
}
}
}
};
In addition to preventing the selection I added the nicety of disabling the Open button to avoid confusion.
Credit for the disabling open button --> Disable Open button in JFileChooser?
As the title states, is there a way to select multiple directories at once (all sub-directories immediately within a primary directory) with JFileChooser so I don't have to re-open the file chooser window for each directory?
Once again I've solved my own question after asking it.
The thing that was preventing me from getting it to work previously was I was using the check for multi-select rather than the set for multi-select, and apparently was using that wrong as well as I kept getting an error. Anyway, the working version is below:
class AddDirectory implements ActionListener {
public void actionPerformed(ActionEvent ae) {
File[] theDir = null;
theDir = selectDir();
if(theDir != null) {
for(File z : theDir) {
String[] curRow = { z.toString(), "Waiting"};
dlm.addRow(curRow);
}
}
return;
}
private File[] selectDir() {
JFileChooser fileChooser = new JFileChooser(lastDir);
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int showOpenDialog = fileChooser.showOpenDialog(null);
if (showOpenDialog != JFileChooser.APPROVE_OPTION) {
return null;
}
File[] uploadDir = fileChooser.getSelectedFiles();
lastDir = new File(uploadDir[uploadDir.length-1].getParent());
return uploadDir;
}
}
Once I get the directories, they're loaded into a JTable to be modified before running the rest of my code on them.
I am trying to Open a file with specific extension ( .fcg or .wtg ) using file Dialog
is there a way to do it ??
If you can use JFileChooser you can use JFileChooser.addChoosableFileFilter() to filter files by extension.
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new FileFilter() {
#Override
public String getDescription() {
return "*.fct, *.wtg";
}
#Override
public boolean accept(File f) {
return f.getName().endsWith(".fcg") ||
f.getName().endsWith(".wtg");
}
});
You can use this this code to choose a file and read
public void openFile() throws Exception {
int rowCount = 0;
int rowNo = 2;
String id = "";
String name = "";
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(new JPanel());
if (result == JFileChooser.APPROVE_OPTION) {
String file = String.valueOf(fc.getSelectedFile());
File fil = new File(file);
System.out.println("File Selected" + file);
FileInputStream fin = new FileInputStream(fil);
int ch;
while ((ch = fin.read()) != -1) {
System.out.print((char)ch);
}
} else {
}
}
As this is google search #1 for me, this is the solution which worked best for me:
How to restrict file choosers in java to specific files
specifics:
JFileChooser open = new JFileChooser(openPath);
FileNameExtensionFilter filter = new FileNameExtensionFilter("PLSQL Files", "sql", "prc", "fnc", "pks"
, "pkb", "trg", "vw", "tps" , "tpb");
open.setFileFilter(filter);