1. Get all files or folders in the specified directory
1 Packagecn.itcast_01;2 ImportJava.io.File;3 Importjava.io.IOException;4 /**5 * Requirements: Gets all files and directories in the specified directory (returns an array of names or a file array)6 */7 Public classFileDemo5 {8 Public Static voidMain (string[] args) {9 //To create a file object and specify an abstract path nameTenFile File =NewFile ("E:"); One //list () returns an array of names AString[] s =file.list (); - for(String string:s) { - System.out.println (string); the } -System.out.println ("--------"); -file[] ListFile =file.listfiles (); - for(File f:listfile) { + System.out.println (F.getname ()); - System.out.println (F.getpath ()); + } A } at}
2. Get the specified file under the specified directory
1 Packagecn.itcast_01;2 ImportJava.io.File;3 Importjava.io.IOException;4 /**5 * Requirements: Get all files in the specified directory ending in. jpg6 */7 Public classFileDemo6 {8 Public Static voidMain (string[] args)throwsIOException {9 //To create a file object specifying an abstract path nameTenFile File =NewFile ("E:"); One //get all content in the specified directory (file array) Afile[] Files =file.listfiles (); - //iterate through the array and determine if the condition is met - for(File f:files) { the if(F.isfile ()) { - if(F.getname (). EndsWith (". jpg")){ - System.out.println (F.getname ()); - } + } - } + } A}
1 Packagecn.itcast_01;2 ImportJava.io.File;3 ImportJava.io.FilenameFilter;4 Importjava.io.IOException;5 /**6 * File name filter7 * Return directly to the document that meets the criteria8 */9 Public classFileDemo7 {Ten Public Static voidMain (string[] args)throwsIOException { One //defining a File object specifying a path AFile File =NewFile ("E:"); - //query all files that meet the criteria -String[] s = file.list (NewFilenameFilter () { the - Public BooleanAccept (File dir, String name) { - /*File File = new file (dir,name); - Boolean Flag1 = File.isfile (); + Boolean flag2 = Name.endswith (". jpg"); - return flag1&&flag2;*/ + return NewFile (dir, name). Isfile () && name.endswith (". jpg"); A } at }); - for(String string:s) { - System.out.println (string); - } - } -}
18th Java I/O stream (2)