简体   繁体   English

而循环背景工作者坏了

[英]While loop background worker broken

I recently made a application which makes backups for websites. 我最近制作了一个可以备份网站的应用程序。 There is one part which makes backups for the website and one part for the databases. 有一部分为网站进行备份,为数据库进行备份。

After I had the application running with hard coded data I decided it would be better to use a .txt file to read values out of so there is no need to change the data in the java application. 在应用程序使用硬编码数据运行后,我决定最好使用.txt文件读取值,因此无需更改Java应用程序中的数据。 This so that you don' t have to recompile the application everytime you add a website. 这样一来,您不必在每次添加网站时都重新编译应用程序。

After I did add that .txt reade my while loop stopped working and I had no idea why. 在添加完.txt后,我的while循环停止工作,我不知道为什么。 Maybe I made a basic mistake but I don't see what. 也许我犯了一个基本的错误,但是我不明白是什么。 I hope you can help. 希望您能提供帮助。

I included a if function because the reading of the text file reads stuff twice so it won't try and open datbases with the name root: 我包含了一个if函数,因为读取文本文件会读取两次,因此它不会尝试打开名称为root的datbases:

if (!"root".equals(dbName)) {
  executeCmd = init + command;
  String printDate = new SimpleDateFormat(" yyyy-MM-dd - HH  mm ss").format(Calendar.getInstance().getTime());
  JTextArea.append("\n" + printDate + executeCmd);
  /*NOTE: Executing the command here*/
  Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
  processComplete = runtimeProcess.waitFor();
}

I thought it might be this but when I disable it nothing changes. 我以为可能是这样,但是当我禁用它时,没有任何变化。

I currently have this code(I disabled the ip adress etc) 我目前有此代码(我禁用了IP地址等)

public class executeCmd1 {
    public String dbName;
    public String dbUser;
    public String part1;
    public String part2;
    public String executeCmd;
    public int processComplete;

    public void executeCmd1() {
        worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                while (true) {
                    System.out.println("Tekst1");
                    try {
                        System.out.println("Tekst2");
                        System.out.println("Reading File from Java code");
                        //Name of the file
                        //*NOTE: Getting path to the Jar file being executed*/
                        //*NOTE: YourImplementingClass-> replace with the class executing the code*/
                        CodeSource codeSource = executeCmd1.class.getProtectionDomain().getCodeSource();
                        File jarFile = new File(codeSource.getLocation().toURI().getPath());
                        String jarDir = jarFile.getParentFile().getPath();

                        String fileName = "Textfile\\textfile.txt";
                        //Create object of FileReader
                        FileReader inputFile = new FileReader(fileName);


                        //Instantiate the BufferedReader Class
                        BufferedReader bufferReader = new BufferedReader(inputFile);

                        //Variable to hold the one line data
                        String line;

                        // Read file line by line and print on the console
                        line = bufferReader.readLine();
                        String[] strs = line.split("-");
                        System.out.println("Substrings length:" + strs.length);
                        for (int i = 0; i < strs.length; i++) {
                            String onderdelen = (strs[i] + "-" + strs[(i + 1)]);

                            String[] parts = onderdelen.split(Pattern.quote("-"));
                            part1 = parts[0];
                            part2 = parts[1];
                            System.out.println(part1 + " " + part2);

                            //Close the buffer reader
                            bufferReader.close();

                            /*NOTE: Creating Database Constraints*/
                            dbName = part1;
                            dbUser = part2;

                            /*NOTE: Creating Path Constraints for folder saving*/
                            //*NOTE: Here the backup folder is created for saving inside it*/
                            String folderPath = jarDir + "\\backup";

                            /*NOTE: Creating Folder if it does not exist*/
                            File f1 = new File(folderPath);
                            f1.mkdir();

                            /*NOTE: Creating Path Constraints for backup saving*/
                            //*NOTE: Here the backup is saved in a folder called backup with the name backup.sql*/
                            String init = "cmd /c start timeout 0 & cd /d C:\\xampp\\mysql\\bin\\ & ";
                            String checkoutDate = new SimpleDateFormat(" yyyy-MM-dd - HH  mm ss").format(Calendar.getInstance().getTime());
                            String command = "mysqldump -P 3306 -h 192.168.50.166 -u " + dbUser + " --databases " + dbName + " -r \"%cd%\\backup\\backup " + checkoutDate + dbName + " file.sql\" & start cmd /c echo fisished ^& timeout 5";
                            JTextArea.append("\n Er wordt een backup gemaakt van " + dbName + " en op de gebruiker " + dbUser);
                            /*NOTE: Used to create a cmd command*/
                            if (!"root".equals(dbName)) {
                                executeCmd = init + command;
                                String printDate = new SimpleDateFormat(" yyyy-MM-dd - HH  mm ss").format(Calendar.getInstance().getTime());
                                JTextArea.append("\n" + printDate + executeCmd);
                                /*NOTE: Executing the command here*/
                                Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
                                processComplete = runtimeProcess.waitFor();

                            }
                            /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
                            if (processComplete == 0) {
                                String printDate = new SimpleDateFormat(" yyyy-MM-dd - HH  mm ss").format(Calendar.getInstance().getTime());
                                JTextArea.append("\n" + printDate + " Backup van datbase compleet");
                            } else {
                                String printDate = new SimpleDateFormat(" yyyy-MM-dd - HH  mm ss").format(Calendar.getInstance().getTime());
                                JTextArea.append("\n" + printDate + " Backup van database mislukt");
                            }
                            Thread.sleep(4000);
                        }

                    } catch (URISyntaxException | IOException | InterruptedException ex) {
                        return null;

                    }
                    System.out.println("Tekst3");
                }
            }

        };
        worker.execute();
        System.out.println("Tekst4");
    }
}

If necessary I can provide the code before I uncluded the text file to show the difference. 如有必要,我可以在取消文本文件显示差异之前提供代码。

There was a problem in the for loop which read values out of the .txt file. for循环中存在一个问题,该问题从.txt文件中读取值。

It was searching for values which weren't there so it crashed in the for loop. 它正在寻找不存在的值,因此在for循环中崩溃了。

The fixe of that loop looks like this. 该循环的修复程序如下所示。

for (int i = 0; i < (strs.length - 1); i++) {
System.out.println("start of for loop");
String onderdelen = (strs[i] + "-" + strs[(i + 1)]);

You provided very detailed code, maybe you could strip down your example a bit. 您提供了非常详细的代码,也许您可​​以简化一下示例。

I think the problem is that you open the file, read one line, split the line and for each substring you close the BufferedReader. 我认为问题是打开文件,读取一行,拆分一行,然后为每个子字符串关闭BufferedReader。 You should only close the BufferedReader once. 您只应关闭BufferedReader一次。

My suggestion is to use java.util.Properties to read the file (Properties.load(Reader)). 我的建议是使用java.util.Properties读取文件(Properties.load(Reader))。 Then you can read the values in your File with getProperty(). 然后,您可以使用getProperty()读取文件中的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM