Skip to content

Instantly share code, notes, and snippets.

@altimmons
Created September 15, 2019 05:44
Show Gist options
  • Save altimmons/5c66c8a2e74333f4e814e8a17347238a to your computer and use it in GitHub Desktop.
Save altimmons/5c66c8a2e74333f4e814e8a17347238a to your computer and use it in GitHub Desktop.
Iterates a filename
/**
* Rather unneccessary, but delightfully interesting (and efficient) way to
* iterate the number at the end of a file name. At least I expect it to be
* efficient since it utilizes a single character buffer all the way through.
*
* It does this by using, underneath everything, javas fast array copy methods
* via StringBuilder, and then through slicing and reversing the string to
* abstract out the number at the end of a fileName. So a File Name of the
* format FileName1234.txt will automatically be parsed and return
* FileName1235.txt.
*
* Not all possible edge cases have been investigated however.
*
* @param fileName
* @return a new FilenName, one greater.
*/
static String fileNameIterator( String fileName ){
Pattern COMPILE =
Pattern.compile( "(\\.)" );
String defaultFileName = "LogFile765.txt";
String[] fn = COMPILE.split( fileName );
//48-57
//fn[0].charAt( (fn[0].length()-1) )
System.out.println( fn.length );
String temp = fn[ 0 ];
StringBuilder stringBuilder = new StringBuilder( temp );
temp = stringBuilder
.reverse()
.toString();
stringBuilder.setLength( 0 );
while( Character.isDigit( temp.charAt( 0 ) ) ){
stringBuilder.append( temp.charAt( 0 ) );
temp = temp.substring( 1 ); //cut off one digit from the front
}
if( stringBuilder.length() >= 1 ){
stringBuilder
.reverse()
.replace( 0 , stringBuilder.length() ,
String.valueOf( Integer.parseInt( stringBuilder.toString() ) + 1 )
)
.reverse() //reverse it backwards again since filename is still
// rev.
.append( temp ) //append the nonnumerial part
.reverse()
.append( "." ) //add the extension
.append( fn[ 1 ] ); //reappend the filename
} else{
stringBuilder
.append( fn[ 0 ] )
.append( 001 )
.append( "." )
.append( fn[ 1 ] );
}
return stringBuilder.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment