Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 177
  • Last Modified:

Code to store filename from folder X to a XML file

Hello all

My problem is that I need to store all file names that is in folder X(preferebly files in subfolders aswell) to a XML file.

So I need some procedure or method that will look through all files in a folder and insert that filename in a String, which then can be stored in a XML file.

--
Thanks for all potential help I can get ;)
0
Idarhillgaar
Asked:
Idarhillgaar
  • 3
  • 3
1 Solution
 
aozarovCommented:
import java.io.*;

public class ListFiles
{
      public static void main(String st[]) throws Exception
      {
            StringBuffer stBuff = new StringBuffer();
            listFiles(new File(st[0]), stBuff);
            System.out.println(stBuff);
      }

      public static void listFiles(File from, StringBuffer stBuff) throws IOException
      {
            if (from.isDirectory())
            {
                  File[] files = from.listFiles();
                  for (int i = 0; i < files.length; i++)
                        listFiles(files[i], stBuff);

                  return;
            }
            
            stBuff.append(from.getPath()).append('\n');
      }
}
0
 
IdarhillgaarAuthor Commented:
Hello

I get an exception error when I'm parsing this code into my builder.

'Exception in thread main java.lang.ArrayIndexOutOfBoundsException: 0
at ListFiles.main(ListFiles.java:8)'

--
I don't really have the insight to correct this code, and how would I set the directory to whatever I want?

thanks again.
Idar
0
 
aozarovCommented:
You get the exception because this program requires the directory to list as an argument.
Hence when you run it you should do something like:
java ListFiles <here_you_should_put_the_directory_path_you_want_to_list>
If you don't want to pass this directory as a command line argument then  you can replace
listFiles(new File(st[0]), stBuff);
with
listFiles(new File(<here_you_should_put_the_directory_path_you_want_to_list>), stBuff);

Basically st[0] get replaced with the first argument in the command line. (and you get the exception if you provide none).
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
IdarhillgaarAuthor Commented:
I'll get right to it, thanks for your answers.

--
Idar
0
 
IdarhillgaarAuthor Commented:
It worked like a dream, thanks again.
0
 
aozarovCommented:
:-)
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now