用带有斜杠的String变量替换硬编码字符串

时间:2014-07-31 05:29:33

标签: java regex

我有以下代码,我试图用变量“ dumppath ”替换转储路径,该变量具有与命令中的字符串完全相同的字符,但当我将其替换为变量,它总是给我一个IOException,它说系统找不到指定的文件。但是使用硬编码路径它可以正常工作。

public String dumppath = "C:\\wamp\\bin\\mysql\\mysql5.6.12\\bin\\mysqldump";

public void backupDatabase() {//GEN-FIRST:event_jButton1ActionPerformed

        try {

            int processComplete; // to verify that either process completed or not

            //Process runtimeProcess = Runtime.getRuntime().exec("C:\\wamp\\bin\\mysql\\mysql5.6.12\\bin\\mysqldump -u root mysql -r F:/backup.sql");
            Process runtimeProcess = Runtime.getRuntime().exec("'"+dumppath+"' -u root mysql -r F:/backup.sql");
// call the mysqldump in terminal and execute it
            processComplete = runtimeProcess.waitFor();//store the state in variable

            if (processComplete == 1) {//if values equal 1 process failed

                JOptionPane.showMessageDialog(null, "Backup Failed");//display message
            } else if (processComplete == 0) {//if values equal 0 process failed
                System.out.println("Backup up : "+backuppath);
                System.out.println("Dump Path : "+dumppath);
                JOptionPane.showMessageDialog(null, "\n Backup created Successfully..\n Check the Backup File in the D: Directory named as backup.sql");
//display message
            }

        } catch (Exception e) {

            JOptionPane.showMessageDialog(null, e);//exeception handling

        }

// TODO add your handling code here:
    }

2 个答案:

答案 0 :(得分:2)

 Process runtimeProcess = Runtime.getRuntime().exec(
   "C:\\wamp\\bin\\mysql\\mysql5.6.12\\bin\\mysqldump -u root mysql -r F:/backup.sql");
 Process runtimeProcess = Runtime.getRuntime().exec(
   "'"+dumppath+"' -u root mysql -r F:/backup.sql");

这些调用中的第一个在路径周围没有单引号。

答案 1 :(得分:2)

Process runtimeProcess = Runtime.getRuntime().exec( "'"+dumppath+"' -u root mysql -r F:/backup.sql");

相同
Process runtimeProcess = Runtime.getRuntime().exec(
 "'C:\\wamp\\bin\\mysql\\mysql5.6.12\\bin\\mysqldump' -u root mysql -r F:/backup.sql");

与硬编码字符串相比,它还有两个单引号。

要获取原始字符串,您应该尝试类似

的内容
String dumppath = "C:\\wamp\\bin\\mysql\\mysql5.6.12\\bin\\mysqldump";
Process runtimeProcess = Runtime.getRuntime().exec( dumppath+" -u root mysql -r F:/backup.sql");

String command = "C:\\wamp\\bin\\mysql\\mysql5.6.12\\bin\\mysqldump -u root mysql -r F:/backup.sql";
Process runtimeProcess = Runtime.getRuntime().exec(command);