linux讀檔案列表和java讀檔案列表
阿新 • • 發佈:2019-02-01
linux
1、判斷一個檔案或資料夾
if test -f filename ;then echo "true";else echo "false"; fi
如果filename是個檔案列印true,否則列印false
if test -d dir ;then echo "true";else echo "false"; fi
如果dir是個資料夾列印true,否則列印false
2、列印當前目錄下所有檔案和資料夾名
for fn in *; do file=$fn; echo $file; done
3、遞迴列印當前資料夾下所有檔名和資料夾名以及資料夾下的檔案
function scandir() {
dir=$1;
for fn in $dir/*;
do echo $fn;
if test -d $fn;
then
new_dir="$fn"
scandir $new_dir
fi done;
}
scandir /Users/zrb/shelltest
java
1、判斷一個檔案或資料夾
2、列印當前目錄下所有檔案和資料夾名
3、遞迴列印當前資料夾下所有檔名和資料夾名以及資料夾下的檔案
import java.io.File; public class TFile { public static void scandir(File file) { File[] files = file.listFiles(); for (File f : files) { if (f.isFile()) { System.out.println(f.toString() + ".isFile()"); } if (f.isDirectory()) { System.out.println(f.toString() + ".isDirectory()"); scandir(f); } } } public static void main(String[] args) { File file = new File("/Users/zrb/shelltest"); if (file.exists()) { System.out.println("file.exists()"); scandir(file); } } }