I'm not a really good Java programmer and I need to know how I can print out all the files in a single folder. See the code below:
for(int i=0;i<folder.number_of_files;i++){
System.out.println(filename[i]);
}
Thanks for your time
Easiest way would be to use File#listFiles
. And if you're using Java 7, see this for changes to the file I/O library. For instance,
File folder = ...;
for(File f : folder.listFiles())
{
System.out.println(f.getName());
}
Note that this will not grab the contents of any sub-folders within the folder
directory.
File file = new File("C:\\");
File[] files = file.listFiles();
for (File f:files)
{
System.out.println(f.getAbsolutePath());
}
listFiles()
has more options. see the documentation here
If you also want to check subfolders below example runs a recursive and check all files under Desktop and its subfolders and writes into a list.
private static String lvl = "";
static BufferedWriter bw;
private static File source = new File("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop\\New folder\\myTest.txt");
public static void main(String[] args) throws IOException {
bw = new BufferedWriter(new FileWriter(source));
checkFiles(new File("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop"), 0);
bw.flush();
bw.close();
lvl = null;
}
static void checkFiles(File file, int level) throws IOException{
if(!file.exists()){
return;
}
for(String s:file.list()){
if(new File(file.getPath() + "\\" + s).isDirectory()){
bw.newLine();
bw.write(lvl + "Directory: " + s);
lvl += " ";
checkFiles(new File(file.getPath() + "\\" + s), level+1);
}else{
bw.newLine();
bw.write(lvl + "File: " + s);
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.