1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2024-06-24 06:03:28 +00:00
CC-Tweaked/src/main/java/dan200/computercraft/shared/util/IDAssigner.java

114 lines
3.3 KiB
Java
Raw Normal View History

package dan200.computercraft.shared.util;
import dan200.computercraft.ComputerCraft;
import java.io.*;
public class IDAssigner
{
2017-05-01 14:48:44 +00:00
private IDAssigner()
{
}
2017-05-01 14:48:44 +00:00
public static int getNextIDFromDirectory( File dir )
{
return getNextID( dir, true );
}
2017-05-01 14:48:44 +00:00
public static int getNextIDFromFile( File file )
{
return getNextID( file, false );
}
2017-05-01 14:48:44 +00:00
private static int getNextID( File location, boolean directory )
{
// Determine where to locate ID file
File lastidFile;
2017-05-01 14:48:44 +00:00
if( directory )
{
location.mkdirs();
lastidFile = new File( location, "lastid.txt" );
}
else
{
location.getParentFile().mkdirs();
lastidFile = location;
}
2017-05-01 14:48:44 +00:00
// Try to determine the id
int id = 0;
if( !lastidFile.exists() )
{
// If an ID file doesn't exist, determine it from the file structure
if( directory && location.exists() && location.isDirectory() )
{
String[] contents = location.list();
for( String content : contents )
2017-05-01 14:48:44 +00:00
{
try
{
int number = Integer.parseInt( content );
2017-05-01 14:48:44 +00:00
id = Math.max( number + 1, id );
}
catch( NumberFormatException e )
{
ComputerCraft.log.error( "Unexpected file '" + content + "' in '" + location.getAbsolutePath() + "'", e );
2017-05-01 14:48:44 +00:00
}
}
}
}
else
{
// If an ID file does exist, parse the file to get the ID string
String idString;
2017-05-01 14:48:44 +00:00
try
{
FileInputStream in = new FileInputStream( lastidFile );
InputStreamReader isr;
try
{
isr = new InputStreamReader( in, "UTF-8" );
}
catch( UnsupportedEncodingException e )
{
isr = new InputStreamReader( in );
}
try( BufferedReader br = new BufferedReader( isr ) )
{
idString = br.readLine();
}
2017-05-01 14:48:44 +00:00
}
catch( IOException e )
{
ComputerCraft.log.error( "Cannot open ID file '" + lastidFile + "'", e );
2017-05-01 14:48:44 +00:00
return 0;
}
2017-05-01 14:48:44 +00:00
try
{
id = Integer.parseInt( idString ) + 1;
}
catch( NumberFormatException e )
{
ComputerCraft.log.error( "Cannot parse ID file '" + lastidFile + "', perhaps it is corrupt?", e );
2017-05-01 14:48:44 +00:00
return 0;
}
}
2017-05-01 14:48:44 +00:00
// Write the lastID file out with the new value
try
{
BufferedWriter out = new BufferedWriter( new FileWriter( lastidFile, false ) );
out.write( Integer.toString( id ) );
out.newLine();
2017-05-01 14:48:44 +00:00
out.close();
}
catch( IOException e )
{
ComputerCraft.log.error( "An error occured while trying to create the computer folder. Please check you have relevant permissions.", e );
2017-05-01 14:48:44 +00:00
}
2017-05-01 14:48:44 +00:00
return id;
}
}