How to retrieve hidden folders using java? - 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]);
}
}
}

Related

How to dynamically rename csv exports, when using csv writer in Java

I have the below code which exports a Jtable as Excel csv export.
I tried appending the file (boolean true), but the append happens within the same file itself.
public static boolean exportToCSV(JTable table,String pathToExportTo) {
try {
TableModel model = table.getModel();
FileWriter csv = new FileWriter(new File("C:/Users/user/Desktop/test.csv"));
for (int i = 0; i < model.getColumnCount(); i++) {
csv.write(model.getColumnName(i) + ",");
}
csv.write("\n");
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
csv.write(model.getValueAt(i, j).toString() + ",");
}
csv.write("\n");
}
csv.close();
JOptionPane.showMessageDialog(null,"Export Successful!");
return true;
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,"Error! Excel cannot be exported!");
}
return false;
This is working fine, but this overwrites the existing file. I would want this to be exported as a different file and probably rename as text(1).csv
You could use a method to compute report output file:
File resolveFileName(){
String directory ="C:/Users/user/Desktop/";
File res = new File(directory + "test.csv");
if(!res.exists()){
return res;
}
int filesInDirectoryCount = (new File(directory)).listFiles().length;
String fileName = "test_"+filesInDirectoryCount+".csv";
return new File(directory+fileName);
}
Usage:
FileWriter csv = new FileWriter(resolveFileName);
This will add a numer to the file name, based on numer of files in this directory. So it should help with this problem.

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;
}

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){
}

Readin from /data/dalvik-cache JavaNullPointer

I'm trying to list all files in /data/dalvik-cache folder but i keep getting NullPointerException
List<String> dalvikFiles = new ArrayList<String>();
for (String dir : dalvikPath) {
File folder = new File(dir);
File list[] = folder.listFiles();
for( int i=0; i< list.length; i++)
{
dalvikFiles.add( list[i].getName() );
}
}
The array dalvikPath contains /data/dalvik-cache
I request su before trying to list and I think i have all the permissions in my manifest.
I think you need to check directory is exist or not . then you can get list of files
File folder = new File(dir);
if(folder.exists()){
File list[] = folder.listFiles();
if(list.length>0{
for( int i=0; i< list.length; i++){
}
}
}else{
}
Ok so i've modified my code and now i don't have javanullpointer but i don't "find" an files in the folders...
List<String> dalvikFiles = new ArrayList<String>();
for (String dir : dalvikPath) {
log.append("Reading " + dir + "\n");
File folder = new File(dir);
if (folder.exists() && folder.isDirectory()){
try{
File list[] = folder.listFiles();
for( int i=0; i< list.length; i++)
{
dalvikFiles.add( list[i].getName().toString() );
log.append(list[i].getName().toString() +"\n");
}
}
catch ( Exception e) {
}
}
else {
log.append("Folder " + dir + "doesn't exist.\n");
}

JFileChooser shows only d: drive content

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

Categories