/*
* Created on 13.05.2004
*/
package beziermanager.io;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* @author Benjamin Sigg
* @version 1.0
*/
public class IniReader {
public static Properties readIni( File file ) throws IOException {
Properties prop = new Properties();
BufferedInputStream in = new BufferedInputStream( new FileInputStream( file ));
StringBuffer buffer = new StringBuffer();
boolean normalComment = false;
boolean multiLineComment = false;
int read = in.read();
char last = (char)read;
while( read != -1 ){
read = in.read();
char newChar = (char)read;
if( normalComment ){
if( newChar == '\n' || newChar == '\r' ){
normalComment = false;
read = jump( in, 1 );
newChar = (char)read;
}
}
else if( multiLineComment ){
if( last == '*' && newChar == '/'){
multiLineComment = false;
read = jump( in, 1 );
newChar = (char)read;
}
}
else{
if( last == '/' && newChar == '*' ){
multiLineComment = true;
read = jump( in, 1 );
newChar = (char)read;
}
else if( last == '/' && newChar == '/' ){
normalComment = true;
read = jump( in, 1 );
newChar = (char)read;
}
else{
if( read == -1 || newChar == '\n' || newChar == '\r' ){
if( buffer.length() > 0 ){
buffer.append( last );
finish( prop, buffer );
buffer = new StringBuffer();
read = jump( in, 1 );
newChar = (char)read;
}
}
else if( !(last == '\n') && !(last == '\r') )
buffer.append( last );
}
}
last = newChar;
}
in.close();
return prop;
}
private static int jump( BufferedInputStream in, int n ) throws IOException{
int read = -1;
for( int i = 0; i < n; i++ )
read = in.read();
return read;
}
private static void finish( Properties prop, StringBuffer buffer ) throws IOException {
int index = buffer.indexOf( "=" );
if( index == -1 )
throw new IOException("Non valid line: " + buffer );
String key = mini( buffer.substring( 0, index ) );
String value = mini( buffer.substring( index+1 ) );
if( key.length() == 0 )
throw new IOException("Non valid key: empty" );
prop.put( key, value );
}
private static String mini( String original ){
while( original.endsWith( " " ) || original.endsWith( "\t" ))
original = original.substring( 0, original.length()-1 );
while( original.startsWith( " " ) || original.startsWith( "\t"))
original = original.substring( 1 );
return original;
}
}