(Java) Gets all the file names of a specified type under a folder and returns the available names as appropriate

Source: Internet
Author: User
Tags dateformat
Http://hi.baidu.com/pannijingling/blog/item/28920202733bb7fe09fa936f.html (Java) gets all the file names of a specified type under a folder. and return the available names as appropriate

Check if the specified directory on the disk already has a file with the same name (this code is checking for a. jpg file type), there are three scenarios:
* 1: Does not exist, returns the name of the query
such as: Enter ABC, return ABC
* 2: There is a file with the same name, return "The predefined name + current date +001" new name
For example: There is a file called Abc.jpg, enter ABC, return ABC20101227001
* 3: Multiple files with the same prefix name, then return a number larger than the largest file name

such as: The existence of abc.jpg,abc20101227001,abc20101227002, ...,abc201012270023 file, enter ABC, return to Abc20101 227024

====================== code starts ==================

Import java.io.*;
Import Java.text.DateFormat;
Import Java.text.SimpleDateFormat;
Import java.util.ArrayList;
Import Java.util.Date;
Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;

Public class Filedirectorysearch {

/**
* Create a method for querying files in the specified directory
*
* @param alllist
* Specify Directory
* @param endname
* Specify a file that ends with ""
* Number of documents received @return
*/
public int Findtxtfilecount (File alllist, String endname) {
int textcount = 0;
Create an array of filearray names
file[] Filearray = Alllist.listfiles ();
If you pass in a file as an object, Alllist returns 0.
if (null = = Filearray) {
return 0;
}
Files in the partial calendar directory
for (int i = 0; i < filearray.length; i++) {
If it's a directory
if (Filearray[i].isdirectory ()) {
System.out.println ("Directory:" +filearray[i].getabsolutepath ());
Recursive call
Textcount + = Findtxtfilecount (Filearray[i].getabsolutefile (),
Endname);
If the file
else if (Filearray[i].isfile ()) {
If the file that ends with ""
if (Filearray[i].getname (). EndsWith (Endname)) {
Presentation file
System.out.println ("EXE file:"
+ Filearray[i].getabsolutepath ());
Add all files that end with ""
textcount++;
}
}
}
return textcount;

 }

/**
* Find in this folder
*
* @param s
* String file name
* @return file[] found files
*/
public static file[] GetFiles (String s) {
Return GetFiles ("./", s);
}

 /**
  * Get files can be found according to regular expressions
  *
  * @param dir
  *             String folder name
  * @param s
  *             String to find the file name, with *.? Files found in fuzzy query
  * @return file[]
  */
 public static file[] GetFiles (String dir, string s) {
&nb sp; //Start folder
  file file = new file (dir);
  s = S.replace ('. ', ' # ');
  s = S.replaceall ("#", "////.");
  s = s.replace (' * ', ' # ');
  s = S.replaceall ("#", ". *");
  s = S.replace ('? ', ' # ');
  s = S.replaceall ("#", ".?");
  s = "^" + S + "$";

Pattern p = pattern.compile (s);
ArrayList list = filepattern (file, p);
file[] Rtn = new file[list.size ()];
List.toarray (RTN);
return RTN;
}

/**
* @param file Start folder path
* @param pattern Match type
* @return ArrayList folders under its folder
*/
private static ArrayList Filepattern (file file, pattern p) {
To determine if the path passed in is null
if (file = = null) {
return null;
else if (File.isfile ()) {//test whether the file represented by this abstract path name is a standard file
Matcher Fmatcher = P.matcher (File.getname ()); P.matcher (File.getname ()) compiles the given regular expression and attempts to match the given input
if (Fmatcher.matches ()) {//attempt to match the entire region to the pattern
ArrayList list = new ArrayList ();
List.add (file);
return list;
}
else if (file.isdirectory ()) {///test whether the file represented by this abstract path name is a directory
file[] files = file.listfiles (); Gets the absolute path of the file under this directory and returns an array
if (Files!= null && files.length >= 0) {
ArrayList list = new ArrayList ();
for (int i = 0; i < files.length; i++) {
ArrayList rlist = Filepattern (Files[i], p); Recursive call to view files under All folders
if (rlist!= null) {
List.addall (rlist);
}
}
return list;
}
}
return null;
}

/**
* Gets the maximum value in the array
* @param filenames
* @return
*/
Private long Findmaxnumber (string[] filenames) {
String Max=filenames[0];
int temp;
for (int i = 1; i < filenames.length; i++) {
Temp=filenames[i].compareto (max);
if (temp>0) {
Max=filenames[i];
}
}
Return Long.parselong (max);
}

/**
* Check to see if this file already exists on the disk, there are three scenarios:
* 1: If it does not exist, return the predefined name
* 2: If there is a file with the same name, return with the predefined name + current date +001
* 3: If there are more than one file with the same prefix name, the file name that is larger than the most recent file is returned
* @param directory of FilePath files
* @param filename A predefined file name
* @return The final file name
*/
public string Checkfilecount (string FilePath, String fileName) {
Get all of the under XXX directory. JPG type file name (uppercase)
file[] files = Filedirectorysearch.getfiles (FilePath, filename+ "*.jpg");
Get the number of files
int count=files.length;

If you do not have this file, return the file name directly
if (count==0) {
return fileName;
}else if (count==1) {
Get Current date
Date Date =new date ();
Format Date format
DateFormat dateformat=new SimpleDateFormat ("YyyyMMdd");
String Riqi=dateformat.format (date);
riqi+= "001";
Generate a new file name
Filename+=riqi;
return fileName;
}else{
Defines an array of strings to receive the value after the string is intercepted
string[] filenames = new String[count];
Defines the start and end positions of the intercepted string and the length of the filename
int beginindex,endindex,filenamelength;
for (int i = 0; i < files.length; i++) {
Filenames[i]=files[i].tostring ();
System.out.println (filenames[i]+ "");

Gets the location of the first occurrence of the file name
Beginindex=filenames[i].indexof (FileName);
Gets the location of the first occurrence of the file name ". jpg"
Endindex=filenames[i].indexof (". jpg");
Gets the length of the file's name
Filenamelength=filename.length ();
Intercepting strings
Filenames[i]=filenames[i].substring (Beginindex+filenamelength, endindex);
}
Get the latest number and add 1, if the original name is "I Love you 20101225", then the new number is "I love you 20101226", guaranteed not to duplicate the original filename
Long maxnumber= this.findmaxnumber (filenames);
maxnumber++;
Generate a new file name
Filename+=maxnumber;
return fileName;
}
}

public static void Main (string[] args) {
You can initialize the path and file name here to test
String fName = "Beauty";
String Fpath = "g:/picture material/mm";
Filedirectorysearch star = new Filedirectorysearch ();
System.out.println (Star.checkfilecount (Fpath, fName));
}
}

=================== Code End ======================
Note: This part of the content from the network, thanks to the original author's selfless dedication. This code is limited to running normally in a particular environment, name to have a certain naming rules, the number of intercepts can only be numbers and try not to start with 0, otherwise it will change the length of the name (such as do not care about the length of the change, can be ignored here), such as: There is a file numbered a,a0001, the new name returned will be A2 Rather than A0002. Another section of the code is still a lot of imperfections, welcome friends to put forward a good solution, I appreciate it ~.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.