开发者

Check if a file exists, and if so create a new file with a higher number

I'm trying to output a set of points that my program creates, and I would like to be able to run it multiple times without having to manually move the files or rename them.

The files that I output would have a name like "cluster-1.txt" (could be changed if needed). So I need my program to find out if a cluster output file exists, find the file with the highest number and create a file with a higher number.

For example, if the program is running for the first time it would check, find no file and create "cluster-0.txt"; if the program is running for the second time, it would check and find "cluster-0.txt" and create "cluster-1.txt"; if the p开发者_如何学JAVArogram is running for the nth time, it would check and find the file with the highest n value and the create a file called "cluster-n+1.txt".

If possible it should ignore any missing files in the middle. So, if I have cluster-0.txt, cluster-10.txt, and cluster-11.txt it should create cluster-12.txt. This is not essential, though.


  1. Read all files in directory. class File
  2. Parse name of files and retrieve number. class String
  3. Choose only the highest number. class Integer and class Math
  4. If highest number exist create file-[highest number + 1].txt else cluster-1.txt


Simplest is probaby to get all the filenames in your output directory using File.list, then look for the ones that match your pattern, either with hand-coded logic or Regex. Having scanned the whole list, you'll know what's the largest existing number.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜