JFileChooser shows only d: drive content - java

May I know how I can make JFileChooser to show only d: drive content? I cannot see any of its public method enables me to do so.
Thanks.

There is a discussion here with some examples.
class RestrictedWinFileSystemView extends FileSystemView{
private File[] allowed = null;
public RestrictedWinFileSystemView(){
}
public RestrictedWinFileSystemView(File[] allowed){
this.allowed = allowed;
}
// apply filter here
public File[] getRoots(){
if(allowed != null){
return allowed;
}
File[] files = super.getRoots();
java.util.List allow = new ArrayList();
for(int i=0; i<files.length; i++){
File desktop = files[i];
File[] roots = desktop.listFiles();
int rl = roots.length;
for(int j=0; j<rl; j++){
File cr = roots[j];
File[] sroots = cr.listFiles();
if(sroots != null){
for(int k=0; k<sroots.length; k++){
File cr1 = sroots[k];
String path = cr1.getAbsolutePath();
if(path.equals("D:\\"){
allow.add(cr1);
}
}
}
}
}
allowed = (File[])allow.toArray(new File[0]);
return allowed;
}
public File createNewFolder(File dir){
return null;
}
public boolean isHiddenFile(File f) {
return super.isHiddenFile(f);
}
public boolean isRoot(File f){
return super.isRoot(f);
}
}
JFileChooser fc = new JFileChooser(new RestrictedWinFileSystemView());

Single Root File Chooser

Related

How to retrieve hidden folders using java?

public void Process(File aFile) throws IOException, ParseException {
if(aFile.isFile())
{
System.out.println("File name:"+aFile.getAbsolutePath());
}
else if (aFile.isDirectory()) {
File[] listOfFiles = aFile.listFiles((FileFilter) HiddenFileFilter.HIDDEN);
if(listOfFiles!=null) {
for (int i = 0; i < listOfFiles.length; i++)
Process(listOfFiles[i]);
}
File[] listOfFiles1 = aFile.listFiles((FileFilter) HiddenFileFilter.VISIBLE);
if(listOfFiles1!=null) {
for (int i = 0; i < listOfFiles1.length; i++)
Process(listOfFiles1[i]);
}
}
}
Call the function in main as follows
String nam = "E:\\";
File aFile = new File(nam);
Process(aFile);
I am using the above code to retrieve all the file details which is present in E:\. It does not retrieve the hidden folder file details. Can anyone help on this?
Just use aFile.listFiles() without any FileFilter then put path of each hidden folder in a list based on check on isHidden().
Sample code:
public static void process(File aFile){
if (aFile.isFile()) {
System.out.println("File name:" + aFile.getAbsolutePath());
} else if (aFile.isDirectory()) {
if(aFile.isHidden()){
System.out.println(aFile.getAbsolutePath()+"folder is hidden");
}
File[] listOfFiles = aFile.listFiles();
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++)
process(listOfFiles[i]);
}
}
}

Android loading files into array NullPointerException

Hi I am trying load a set of "list" into a String array, and the list are simply .txt documents and I want to use the names of the files as the list name on my display, therefore I need to get all of the files in the folder that I had created named "Lists" and then display them into an arrayadapter.
private String[] getListNames() {
//generates the file containing the list names
File file = new File(this.getFilesDir() +File.separator +"Lists");
System.out.println(file.getAbsolutePath());
File lists[] = file.listFiles();
String names[] = {};
if(lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
line of code in question according to the stacktrace (line 108)
if(lists.length >0){
StackTrace
03-25 04:37:16.981: E/AndroidRuntime(2099): Caused by: java.lang.NullPointerException
03-25 04:37:16.981: E/AndroidRuntime(2099): at dev.shaw.MyShoppingPlanner.List_Activity.getListNames(List_Activity.java:108)
private List<String> myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File( root_sd + "/Lists" ) ;
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
You need to log if files.getFileList() is really returning anything or not:
also
change this:
File lists[] = file.listFiles();
String names[] = {};
if(lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
to
File lists[] = file.listFiles();
String names[] = {};
if(lists != null && lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
P.S: You cannot get the length if the lists array is null in the first place.!
try this one.
//use two boolean variables.
File file;
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
//check if the sdcard is enable or disable in your device
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
private String[] getListNames() {
if (mExternalStorageAvailable) {
File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
if (!path.exists()) {
path.mkdirs();
}
file=path.getAbsolutePath();
}
else {
//use ContextWrapper it a onw way to access internal storage.
ContextWrapper cw = new ContextWrapper(getApplicationContext());
(or)
//generates the file containing the list names
file = new File(this.getFilesDir() +File.separator +"Lists");
if (!file.exists()) {
file.mkdirs();
}
System.out.println(file.getAbsolutePath());
}
File lists[] = file.listFiles();
String names[] = {};
try{
if (lists.length==0)
{
System.out.print("There is no files in the Directory");
}
else{
if(lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
catch(Exception e)
{
e.printStackTrace();
}
}

Return values in recursive function in java

here is a simple function that searches for a file in a given folder and its subfolders i am able to find the file but somehow the return value is a null and can someone also explain what happens in the stack when we use recursive functions if you can relate it to my scenario it would be great...
File getFileInFolder(File folder, String fileName) {
//System.out.println(" PathTo : "+folder.getAbsolutePath());
File [] files = folder.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
return getFileInFolder(files[i],fileName);
} else {
//System.out.println(" file : "+files[i].getName());
if (files[i].getName().equals(fileName)) {
System.out.println(" Found file : "+files[i].getName());
return files[i];
}
}
}
}
return null;
}
Let's say that you're looking for a.txt in the following folder:
root
sub1
b.txt
sub2
a.txt
What your algorithm does is
List the files in root. That returns sub1 and sub2.
Iterate through the files. If the file is a directory, return the result of the method on this directory
So, the algorithm will search only in sub1, and that will return null.
You need to continue searching in other directories if the file wasn't found in the first one:
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
File resultForSubDirectory = getFileInFolder(files[i], fileName);
if (resultForSubDirectory != null) {
return resultForSubDirectory;
} // else: continue looping
}
else {
...
}
}
i have solved it using a bool variable filefound and i break all the loops in the stack, don"t know if it is the best way to do it but it works for me
boolean filefound = false;
File getFileInFolder(File folder, String fileName) {
filefound = false;
//System.out.println(" PathTo : "+folder.getAbsolutePath());
File [] files = folder.listFiles();
File file = null;
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
file = getFileInFolder(files[i],fileName);
if(filefound) {
file= files[i];
break;
}
} else {
//System.out.println(" file : "+files[i].getName());
if (files[i].getName().equals(fileName)) {
System.out.println(" Found file : "+files[i].getName());
file= files[i];
filefound = true;
break;
}
}
}
}
return file;
}

Detecting the last folder from a list

I have several files, thing is that i need to know which one was the last created according to the numbers I give them automatically.
For example if i have: file1, file2, file3 I want to receive the file3. I can't do this with "last modified" because I have other folders and files in the same directory.
Also to this last file I would like to increment his number in 1.
Put the files in a list and sort it lexically, then take the last one.
Ofcourse you have to filter out the ones you are looking for with regex or contains/startswith/endswith
Here is an alternate simple solution.
import java.io.File;
public class FileUtility {
private static final String FOLDER_PAHT = "D:\\Test";
private static final String FILE_PREFIX = "file";
/**
* #param args
*/
public static void main(String[] args) {
int lastFileNumber = getLastFileNumber();
System.out.println("In folder " + FOLDER_PAHT + " last file is " + FILE_PREFIX + lastFileNumber);
if(incrementFileNumber(lastFileNumber)) {
System.out.println("After incrementing the last file becomes : FILE_PREFIX" + lastFileNumber + 1);
} else {
System.out.println("Some error occured while updating file number.");
}
}
private static int getLastFileNumber(){
int maxFileNumber = 0;
File folder = new File(FOLDER_PAHT);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String fileName = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && fileName.contains(FILE_PREFIX)) {
try {
int fileNumber = Integer.parseInt(fileName.substring(FILE_PREFIX.length(), fileName.indexOf(".")));
if(maxFileNumber < fileNumber) {
maxFileNumber = fileNumber;
}
} catch (NumberFormatException e) {
// Because there can be files with starting name as FILE_PREFIX but not valid integer appended to them.
//NOthing to do
}
}
}
return maxFileNumber;
}
private static boolean incrementFileNumber(final int oldNumber) {
File oldfile =new File(FOLDER_PAHT + File.separator + FILE_PREFIX + oldNumber);
File newfile =new File(FOLDER_PAHT + File.separator + FILE_PREFIX + (oldNumber + 1) + ".txt");
return oldfile.renameTo(newfile);
}
}
public static void main (String[] args) throws Exception
{
File foldersContainer = new File("c:/test");
String latestFileName = "";
Integer highestFileNumber = 0;
for (File tmpFile : foldersContainer.listFiles()){
if (tmpFile.isFolder()) {
int currentNumber = extractFileNumber(tmpFile.getName());
if (currentNumber > highestFileNumber){
highestFileNumber = currentNumber;
latestFileName = tmpFile.getName();
}
}
}
latestFileName.replace(highestFileNumber.toString(),
(++highestFileNumber).toString());
System.out.println("Latest file (incremented): " + latestFileName);
}
private static int extractFileNumber(String name){
for (int x=name.length()-1; x >= 0; x--)
if (!Character.isDigit(name.charAt(x)))
return Integer.parseInt(name.substring(x+1));
return -1;
}
If the filename before the last number can contain numbers, then you should use lastIndexOf to be sure of finding only the occurrence you really want to increment.
instead of
latestFileName.replace(highestFileNumber.toString(),
(++highestFileNumber).toString());
you should use
latestFileName = latestFileName
.substring(0,latestFileName.lastIndexOf(highestFileNumber.toString()))
.concat((++highestFileNumber).toString());
Ok, here's an alternative. I'm assuming that the file name is known and they have the same name.
public static void main(String[] args) {
File dir = new File("directory of the files");
File [] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.startsWith("folder");
}
});
for (File file : files) {
System.out.println(file.getName());
}
System.out.println("---------");
List<File> myFile = new ArrayList<>(Arrays.asList(files));
Collections.sort(myFile, new Comparator<File>() {
#Override
public int compare(File f1, File f2) {
// TODO Auto-generated method stub
int numberF1 = Integer.parseInt(f1.getName().replace("folder",""));
int numberF2 = Integer.parseInt(f2.getName().replace("folder",""));
return Integer.compare(numberF1, numberF2);
}
});
for (File file : myFile) {
System.out.println(file.getName());
}
}
Output :
folder10
folder2
folder20
folder250
---------
folder2
folder10
folder20
folder250

Deleting Multiple Files Java (Android)

I'm new to programming Android, and I want to delete Files on the sd-card. This is my current (working) code...
File appvc = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "ApplifierVideoCache");
if (appvc.isDirectory()) {
String[] children = appvc.list();
for (int i = 0; i < children.length; i++) {
new File(appvc, children[i]).delete();
}
}
Now I want to delete multiple files, but dont want to mention each file with that big block. Am I able to combine all files in one variable? Thanks ;)
Make a recursive method:
/*
* NOTE: coded so as to work around File's misbehaviour with regards to .delete(),
* which does not throw an exception if it fails -- or why you should use Java 7's Files
*/
public void doDelete(final File base)
throws IOException
{
if (base.isDirectory()) {
for (final File entry: base.listFiles())
doDelete(entry);
return;
}
if (!file.delete())
throw new IOException ("Failed to delete " + file + '!');
}
Another possibility would be using the Apache commons-io library and calling
if (file.isDirectory())
FileUtils.deleteDirectory(File directory);
else {
if(!file.delete())
throw new IOException("Failed to delete " + file);
}
You should make a method out of this chunk of code, pass file name and call it whenever you like:
public void DeleteFile(String fileName) {
File appvc = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), fileName);
if (appvc.isDirectory()) {
String[] children = appvc.list();
for (int i = 0; i < children.length; i++) {
new File(appvc, children[i]).delete();
}
}
}
File dir = new File(android.os.Environment.getExternalStorageDirectory(),"ApplifierVideoCache");
Then call
deletedir(dir);
public void deletedir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
listFile[i].delete();
}
}
}
or if your folder as sub folders then
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++)
{
if (listFile[i].isDirectory())
{
walkdir(listFile[i]);
} else
{
listFile[i].delete();
}
}
}
For kotlin
Create a array of path list
val paths: MutableList<String> = ArrayList()
paths.add("Yor path")
paths.add("Yor path")
.
.
delete file for each path
try{
paths.forEach{
val file = File(it)
if(file.exists(){
file.delete()
}
}
}catch(e:IOException){
}

Categories