1. Case:
Determine if there is a file with a suffix of. jpg under the F-disk, and if so, output the file name.
2. The case code is as follows:
(1) The idea is: First get all the files and folders encapsulated objects, and then traverse the time, in turn, to determine if the condition is satisfied with the output.
1 PackageCom.himi.filesdemo;2 3 ImportJava.io.File;4 5 6 /**7 * Determine if there is a file with a suffix of. jpg under the F-disk, and if so, output this file name8 * @authorHebao9 *Ten */ One Public classFileDemo4 { A - Public Static voidMain (string[] args) { - //Catalogue of the F-disk packages theFile File =NewFile ("f:\\"); - //get file array for all files and folders in this directory -file[] Files =file.listfiles (); - //traverse the file[] array above + for(File f:files) { - if(F.isfile ()) { + if(F.getname (). EndsWith (". jpg")) { ASystem.out.println ("jpg picture file name:" +f.getname ()); at } - } - } - } - -}
The results are as follows:
(2) The idea is: To obtain the time has been satisfied with the conditions, and then output can.
1 PackageCom.himi.filesdemo;2 3 ImportJava.io.File;4 ImportJava.io.FilenameFilter;5 6 7 /**8 * Determine if there is a file with a suffix of. jpg under the F-disk, and if so, output this file name9 * Ten * Ideas: One * (1) First get all the files and folders encapsulated objects, and then traverse the time, in turn, to determine if the condition is satisfied with the output. A * (2) When the condition has been satisfied, then the output can be. - * @authorHebao - * the */ - Public classFileDemo4 { - - Public Static voidMain (string[] args) { + //ideas (1) - /* + //Catalogue of F-trays A File File = new file ("f:\\"); at //Get file array for all files and folders in this directory - file[] files = file.listfiles (); - //traverse the file[] array above - For (File f:files) { - if (F.isfile ()) { - if (F.getname (). EndsWith (". jpg")) { in System.out.println ("jpg image file name:" +f.getname ()); - } to } + } - */ the * //Ideas (2) $ Panax Notoginseng //Catalogue of the F-disk packages -File File =NewFile ("f:\\"); the //gets a string array of all files and folders in this directory +string[] Strarray = File.list (NewFilenameFilter () { A the Public BooleanAccept (File dir, String name) { + //System.out.println (dir+ "----------" +name); -File File =NewFile (dir,name); $ BooleanFlag1 =file.isfile (); $ BooleanFlag2 = File.getname (). EndsWith (". jpg"); - - returnFlag1 &&Flag2; the } - });Wuyi the //traversing a string array - for(String str:strarray) { Wu System.out.println (str); - } About } $ -}
Run the effect as follows:
Java Fundamentals Hardening IO Flow Note 10:file class output file name case with specified suffix name in specified directory