Adding file names to an array list in java - java

I am currently needing to load the contents of a folders filenames to an arraylist I have but I am unsure as how to do this.
To put it into perspective I have a folder with One.txt, Two.txt, Three.txt etc. I want to be able to load this list into an arraylist so that if I was to check the arraylist its contents would be :
arraylist[0] = One
arraylist[1] = Two
arraylist[3] = Three
If anyone could give me any insight into this it would be much appreciated.

Here's a solution that uses java.io.File.list(FilenameFilter). It keeps the .txt suffix; you can strip these easily if you really need to.
File dir = new File(".");
List<String> list = Arrays.asList(dir.list(
new FilenameFilter() {
#Override public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
}
));
System.out.println(list);

File dir = new File("/some/path/name");
List<String> list = new ArrayList<String>();
if (dir.isDirectory()) {
String[] files = dir.list();
Pattern p = Pattern.compile("^(.*?)\\.txt$");
for (String file : files) {
Matcher m = p.matcher(file);
if (m.matches()) {
list.add(m.group(1));
}
}
}

You can try with
File folder = new File("myfolder");
if (folder.isDirectory())
{
// you can get all the names
String[] fileNames = folder.list();
// you can get directly files objects
File[] files = folder.listFiles();
}

Here's My answer, I've used this before personally to get all the filenames,
to be used in a loadsave function in one of my games.
public void getFiles(String path){
//Put filenames in arraylist<string>
File dir = new File(path);
ArrayList<String> filenames = new ArrayList<String>();
for(File file : dir.listFiles()){
savefiles.add(file.getName());
}
//Check if the files are in the arraylist
for (int i = 0; i < savefiles.size(); i++){
String s = savefiles.get(i);
System.out.println("File "+i+" : "+s);
}
System.out.println("\n");
}
I hope that may have been of use to you C: - Hugs rose

See the Jave File API, particularly the list() function.
File my_dir = new File("DirectoryName");
assert(my_dir.exists()); // the directory exists
assert(my_dir.isDirectory()); // and is actually a directory
String[] filenames_in_dir = my_dir.list();
Now filenames_in_dir is an array of all the filenames, which is almost precisely what you want.
If you want to strip the extensions off the individual filenames, that's basic string handling - iterate over the filenames and take care of each one.

Have a look at java.io.File it gives you all the control you may need.
Here is a URL for it http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html

Related

compare values in an arrayList with c: drive in windows

am trying to compare all the values in my arraylist with all the files in my c:drive
but the code below does not work
List<String> list = new ArrayList<String>();
list.add("*.txt,*.docx");
File file = new File("c:\\*.txt");
if (file.equals(list)) {
System.out.println("file was found");
}else{System.out.println("nothing was found");
}
so the idea is that anytime i run my the code my arraylist would compare itself with my c: drive and list all files that has the extension of "docx and txt" out.
i realised that when i use wildcards it didn't work.
What you need is a FileNameFilter to get all files that pertain to your requirements
Here is an example of getting all *.txt files from current directory. You can implement FileNameFilter to create your own filter that will work on your List.
File f = new File("."); // current directory
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".txt")) {
return true;
} else {
return false;
}
}
};
File[] files = f.listFiles(textFilter);
Hope this helps.

Java iterative reading of Files

at the moment I'm having a problem with writing a tool for my company. I have 384 XML files that i have to read and parse with a SAX Parser into txt files.
What i got until now is the parsing of all XML-Files into one txt File, size 43 MB. With a BufferedReader and line.startsWith i want to extract all relevant information out of the textfile.
Edit: Done
(So my Problem is how to solve this more efficiently. I'm having an idea (but unfortunately not in code as you might think) but i dont know if its possible: I want to iterate through a Directory, find the XML-File i want, then parse it and create a new txt File with the parsed content. If done for all 384 XML files i want the same thing for the 384 txt files, read them with a BufferedReader to get my relevant information. Its important to read them one at a time. Another Problem is the Directory path, its a bit complex: "C:\Users\xxx\Documents\Data\ProjectName\A1\1\1SLin\wanted.xml" for each file there is a own directory. The variable is A1, it reaches from A-P and 1-24. Alternatively I have all the relevant files with thir absolute path in an arraylist, so its also okay to iterate over this list if its easier.)
Edit:
I came to a solution: Below contains the search directories method and a method to parse the xml Files of a List into the same directory with the same filename but another file extension
public List<File> searchFile(File dir, String find) {
File[] files = dir.listFiles();
List<File> matches = new ArrayList<File>();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
matches.addAll(searchFile(files[i], find));
} else if (files[i].getName().equalsIgnoreCase(find)) {
matches.add(files[i]);
}
}
}
Collections.sort(matches);
return matches;
}
public static void main(String[] args) throws IOException {
Import_Files im = new Import_Files();
File dir = new File("C:\\Users\\xxx\\Desktop\\MS-Daten\\");
String name = "snp_result_5815.xml";
List<File> matches = im.searchFile(dir, name);
System.out.println(matches);
for (int i=0; i<matches.size(); i++) {
String j = String.valueOf(i);
String xml_name = matches.get(i).getAbsolutePath();
File f = new File(matches.get(i).getAbsolutePath().replaceFirst(".xml", ".txt"));
System.setOut(new PrintStream(new FileOutputStream(f)));
System.out.println("\nstarting File: "+ i + "\n");
xml_parse myReader = new xml_parse(xml_name);
myReader.setContentHandler(new MyContentHandler());
myReader.setErrorHandler(new MyErrorHandler());
myReader.run();
}
}
The searchFolder method below will take a path and file extension, search the path and all sub-directories, and pass any matching file types to the processFile method.
public static void main(String[] args) {
String path = "c:\\temp";
Pattern filePattern = Pattern.compile("(?i).*\\.xml$");
searchFolder(path, filePattern);
}
public static void searchFolder(String searchPath, Pattern filePattern){
File dir = new File(searchPath);
for(File item : dir.listFiles()){
if(item.isDirectory()){
//recursively search subdirectories
searchFolder(item.getAbsolutePath(), filePattern);
} else if(item.isFile() && filePattern.matcher(item.getName()).matches()){
processFile(item);
}
}
}
public static void processFile(File aFile){
String filename = aFile.getAbsolutePath();
String txtFilename = filename.substring(0, filename.lastIndexOf(".")) + ".txt";
//Do your xml file parsing and write to txtFilename
}
The complexity of the path makes no difference, just specify the root path to search (looks like C:\Users\xxx\Documents\Data\ProjectName in your case) and it will find all the files.

Filter files using a wildcard character (java)

Using a wildcard character I want to process files in a directory. If a wildcard character is specified I want to process those files which match the wildcard char else if not specified I'll process all the files. Here's my code
List<File> fileList;
File folder = new File("Directory");
File[] listOfFiles = folder.listFiles();
if(prop.WILD_CARD!=null) {
Pattern wildCardPattern = Pattern.compile(".*"+prop.WILD_CARD+"(.*)?.csv",Pattern.CASE_INSENSITIVE);
for(File file: listOfFiles) {
Matcher match = wildCardPattern.matcher(file.getName());
while(match.find()){
String fileMatch = match.group();
if(file.getName().equals(fileMatch)) {
fileList.add(file); // doesn't work
}
}
}
}
else
fileList = new LinkedList<File>( Arrays.asList(folder.listFiles()));
I'm not able to put the files that match wildcard char in a separate file list. Pls help me to modify my code so that I can put all the files that match wildcard char in a separate file list. Here I concatenate prop.WILD_CARD in my regex, it can be any string, for instance if wild card is test, my pattern is .test(.)?.csv. And I want to store the files matching this wildcard and store it in a file list.
I just tested this code and it runs pretty well. You should check for logical errors somewhere else.
public static void main(String[] args) {
String WILD_CARD = "";
List<File> fileList = new LinkedList<File>();
File folder = new File("d:\\");
File[] listOfFiles = folder.listFiles();
if(WILD_CARD!=null) {
Pattern wildCardPattern = Pattern.compile(".*"+WILD_CARD+"(.*)?.mpp",Pattern.CASE_INSENSITIVE);
for(File file: listOfFiles) {
Matcher match = wildCardPattern.matcher(file.getName());
while(match.find()){
String fileMatch = match.group();
if(file.getName().equals(fileMatch)) {
fileList.add(file); // doesn't work
}
}
}
}
else
fileList = new LinkedList<File>( Arrays.asList(folder.listFiles()));
for (File f: fileList) System.out.println(f.getName());
}
This returns a list of all *.mpp files on my D: drive.
I'd also suggest using
for (File file : listOfFiles) {
Matcher match = wildCardPattern.matcher(file.getName());
if (match.matches()) {
fileList.add(file);
}
}
I would suggest you look into the FilenameFilter class and see if it helps simplify your code. As for your regex expression, I think you need to escape the "." character for it to work.

read file system structure from java

Is it possible to read all the names of folders (not sub-folders) inside a directory and save the list in an ArrayList, etc ?
e.g- if a directory has the following folders inside it- CLIENT1, CLIENT2, CLIENT3, etc.
I want the ArrayList to be something like this- [CLIENT1, CLIENT2, CLIENT3, etc].
The folders are in an unix server, so either java code or a shell script(bash/tcsh/etc) or their combination would do.
Try this:
File dir = new File("directoryName");
File temp;
String[] children = dir.list();
if (children !=null) {
for (int i=0; i<children.length; i++) {
temp = new File(children[i]);
if(temp.isDirectory()) //add children[i] to arrayList
}
}
The below Java code snippet should help you. It will return the list of all folders within a directory.It may return an empty list based on the manner in which you deal with any possible IO exception.
public List<String> getDirectoriesInFolder(String folderPath)
{
List<String> folderNames = new ArrayList<String>();
try
{
File directory = new File (folderPath);
String[] allFilesInFolder = directory.list();
for(String fileName : allFilesInFolder)
{
File f = new File(fileName);
if(f.isDirectory)
{
folderNames.add(fileName);
}
}
}
catch(IOException iex)
{
//Do any exception handling here...
}
return folderNames;
}
If you want to do it using Shell scripting then the guidance provided on the below links should help you come to a solution:
help with script to list directories
bash: put output from ls into an array
This would feel slightly cleaner to me than a blunt iteration constructing new File() each time.
public class DirFilter implements FileFilter {
public static FileFilter INSTANCE = new DirFilter();
#Override
public boolean accept(File file) {
return file.isDirectory();
}
}
File startDir = .....;
List<File> children = Arrays.asList(startDir.listFiles(DirFilter.INSTANCE));

java listing the txt files in sub folders

Hi I have a jlist and currently it is viewing a folder + subfolders... Now i would like to change this to view the files in the subfolders as well. below please find the code I am currently using:
jList1.setModel(new javax.swing.AbstractListModel()
{
File folder = new File ("/Assignment_Datex/message_outbox/");
File[] listofFiles = folder.listFiles();
// #Override
public int getSize()
{ return listofFiles.length; }
// #Override
public Object getElementAt(int i)
{ return listofFiles[i];}
}
);
Right now as you can see in the screenshot, the Jlist is only viewing the folders and not the files in them... Any help please?
If you want to show all files and folder under some root folder then you should try someting like this...
Get files and folders under root folder.
Loop over them and check if it is file or folder.
If file then just add to list nothing more.
If folder then add it to list and repeat this same steps for that folder until all folder and files are traveled.
I can not produce whole code here but this is a prototype for this:
void addFilesToList(File folder){
File[] listofFiles = folder.listFiles();
for(File file:listofFile){
if(file.isFile()) // --- file
list.add(file.getName());
else{ // --- folder
addFileToList(file);
}
}
}
The above code is not tested so may need to modify it to fit your need.
#Harry Joy is right.
Additionally you can also use FindFile from jakarta project. It can save your time.
You create a constructor to initialise your class, and there you put (tested and working)
// initialize the class variable
listofFiles = new ArrayList();
// initialize with the path
File f = new File("/home/albertmatyi/Work/python/");
// create a temporary list to work with
LinkedList files = new LinkedList();
// fill it with the contents of your path
files.addAll(Arrays.asList(f.listFiles()));
while (!files.isEmpty()) {
// keep removing elements from the list
f = files.pop();
// if it is a directory add its contents to the files list
if (f.isDirectory()) {
files.addAll(Arrays.asList(f.listFiles()));
// and skip the last if
continue;
}
// check if it's a text file, and add it to listofFiles
if (f.getName().endsWith(".txt"))
listofFiles.add(f);
}
EDIT:
Note:
I've changed the type of listofFiles to ArrayList<File>, which has to be initialized in the constructor using:
listofFiles = new ArrayList<File>();
This allows easier manipulation of the data - no need to manually allocate bigger space for when more text files need to be added
I think this is good way to read all .txt files in a folder and sub folder's
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
String name=(path.get(i)).getName();
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(path.get(i));
}
}
}
}
}
if(input.isFile())
{
String name=(input.getName());
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(input);
}
}
}
}
Now you have a list of files that you can do some process on it!

Categories