|
Get Directory
List From Server
How can I get directory list from the server?
With this code you can list all files in a given directory:
Code:
import java.io.File;
public class ListFiles
{
public static void main(String[] args)
{
// Directory path here
String path = ".";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
System.out.println(files);
}
}
}
}
If you want to list only .txt files for example, Use this:
Code:
import java.io.File;
public class ListFiles
{
public static void main(String[] args)
{
// Directory path here
String path = ".";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".txt") ||
files.endsWith(".TXT"))
{
System.out.println(files);
}
}
}
}
}
Note:
You can modify the .txt or .TXT to be whatever file extension you
wish.
Alternative to test for files with a certain ending:
Code:
MyFilter implements FileFilter
{
public boolean accepts(File pathname)
{
if (pathname.endswith(".txt")
|| pathname.endswith(".TXT"))
{
return true;
}
return false;
}
}
Code:
import java.io.File;
public class ListFiles
{
public static void main(String[] args)
{
// Directory path here
String path = ".";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles(new MyFilter());
for (int i = 0; i < listOfFiles.length; i++)
{
System.out.println(listOfFiles[i].getName());
}
}
}
Technically, this code will display folders named hello.txt, or this
is a directory.txt, but I think it's fairly safe to assume that most people
won't name their directories this way.
Do you have a Java Problem?
Ask It in The Java
Forum
Java Books
Java
Certification, Programming, JavaBean and Object Oriented Reference Books
Return to : Java
Programming Hints and Tips
All the site contents are Copyright © www.erpgreat.com
and the content authors. All rights reserved.
All product names are trademarks of their respective
companies.
The site www.erpgreat.com is not affiliated with or endorsed
by any company listed at this site.
Every effort is made to ensure the content integrity.
Information used on this site is at your own risk.
The content on this site may not be reproduced
or redistributed without the express written permission of
www.erpgreat.com or the content authors.
|