I have written a Java class to replace text in file. The file contains database configurations and is as follows:
test.properties
#local
db.url=jdbc:oracle:thin:@localhost:test
#db.user=testa
#db.password=testa
db.user=testb
db.password=testb
#db.user=testc
#db.password=testc
#
is a comment character. Now db schema testb
is in use.
Here is my Java class to switch between schemas
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class SwitchTo
{
public static void main(String[] args)
{
Map<String, String> schemaMap = new HashMap<String, String>();
schemaMap.put("a", "testa");
schemaMap.put("b", "testb");
schemaMap.put("c", "testc");
String newText = "";
for (int i = 0; i < args.length; i++)
{
newText = args[i];
}
String newdb = "";
newdb = schemaMap.get(newText);
if (newdb == null || (newdb != null && newdb.length() <= 0))
{
System.out.println("Schema not available, please select : ");
for (Map.Entry<String, String> entry : schemaMap.entrySet())
{
System.out.println(entry.getKey() + " for " + entry.getValue());
}
return;
}
try
{
BufferedReader file = new BufferedReader(new FileReader("test.properties"));
String total = "";
String line = "";
while ((line = file.readLine()) != null)
{
if (!line.startsWith("#") && line.contains("db.user"))
{
line = "#" + line;
}
if (!line.startsWith("#") && line.contains("db.password"))
{
line = "#" + line;
}
if (line.startsWith("#") && line.contains(newdb))
{
line = line.substring(1);
}
total = total + line + "\n";
}
FileOutputStream File = new FileOutputStream("test.properties");
File.write(total.getBytes());
System.out.println("Switched to schema " + schemaMap.get(newText));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
and I have created a batch file to run this program from command line which is as follows :
switch.bat
java SwitchTo %1
Now when write at command line
c:\> switch a
Then it will comment testb
in the file and testa
will be uncommented.
Please suggest other improvement for this code.
- Is using map for storing schemas is a good choice?
- How can I make it generic to accommodate newly added schemas without need to compile this class again?
- Is there any better algorithm for solving this?