Extracting a database name from a file I am developing a project that converts SQL server file to MySQL file based on some assumptions. I have written a function that takes the string source as input and it extracts the database name. Is there any way to improve the code?

public String getDatabaseNameFromMySqlServerFile(String source) {

    String sourceFile = null;
    String databaseName = "";
    Path file = Paths.get(source);
    try (InputStream in = Files.newInputStream(file);
            BufferedReader reader
            = new BufferedReader(new InputStreamReader(in))) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            if (line.toLowerCase().contains("create database")) {
                String[] Arrline = line.split(" ");
                for (String s : Arrline) {
                    if (!s.toLowerCase().equals("create") &amp;&amp; !s.toLowerCase().equals("database")) {
                        databaseName = s;
                        return s;
                    }
                }
            }
            sourceFile = sourceFile + line;
        }
    } catch (IOException x) {
        System.err.println(x);
    }

    return null;
}
databaseName is a pointless local variable: you can simply delete all lines using it.

The same goes for sourceFile.



Arrline and s are poorly named variables, and s is lowercased twice:


String[] Arrline = line.split(" ");
for (String s : Arrline) {
    if (!s.toLowerCase().equals("create") &amp;&amp; !s.toLowerCase().equals("database")) {
        return s;
    }
}



Cleaning these up the code becomes:

String[] segments = line.split(" ");
for (String origSegment : segments) {
    String segment = origSegment.toLowerCase();
    if (!segment.equals("create") &amp;&amp; !segment.equals("database")) {
        return origSegment;
    }
}




The current method of extracting the database name is quite awkward and inefficient. Look at these steps:


lowercase the line
check if it contains a string
split the line to tokens
for each token


if the lowercased token is neither "create" nor "database" then return it



You can do much better using regular expressions:

Pattern DBNAME_PATTERN = Pattern.compile("create +database +(\\w+)", Pattern.CASE_INSENSITIVE);

private String extractDatabaseName(String input) {
    Matcher matcher = DBNAME_PATTERN.matcher(input);
    if (matcher.find()) {
        return matcher.group(1);
    }
    return null;
}




The initialization of line is unnecessary,
because it gets assigned on the next line anyway:


String line = null;



So a simple declaration is enough:

String line;