简体   繁体   中英

How Can I Split a Long String Into Lines At “),”?

Having a bit of a headache trying to parse a text file correctly, it's a pull from mysql database but the data needs to be changed a fair bit before it can be inserted again.

My program is taking a .txt file and parsing it to produce a .txt file, which is simple enough.

The issue is that it is not splitting the file correctly. The file looks as follows (the middle field of each looks strange because I've changed it to random letters to hide the real data):

(92,'xxxname',4013),(93,'sss-xxx',4047),(94,'xxx-sss',3841),(95,'ssss',2593),(96,'ssss-sss',2587),(97,'Bes-sss',2589),

I want to split it so that it produces a file like:

(92, 'xxxname',4013),

(93, 'sss-xxx', 4047),

(94, 'xxx-sss', 3841),

And so on...

Current code for parsing is as follows:

public void parseSQL(File file) throws IOException {
    Scanner scanner = new Scanner(file);

    while (scanner.hasNext()) {
        String line = scanner.next();
        String[] lines = line.split(Pattern.quote("),"));

        for (String aLine : lines) {
            logLine(aLine);
        }
    }

}

public static void logLine(String message) throws IOException {
    PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), 
         true);
    out.println(message);
    out.close();
}

Currently the output I'm getting is roughly on track but more split up than it should be, and of course the split method is removing the ")," which is unnecessary.

Sample of the current output:

*(1,'Vdddd
Cfffff',1989
(2,'Wdd',3710
(3,'Wfffff
Hffffff
Limited-TLC',3901
(4,'ffffffun88',2714
(5,'ffffff8',1135
(6,'gfgg8*

Been playing around for a while and have done a good bit of searching here and elsewhere but out of ideas, any help would be greatly appreciated.

You can use String.replace . There's also no need to create multiple PrintWriter s and close the stream every time.

public void parseSQL(File file) throws IOException {
    Scanner scanner = new Scanner(file);

    PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
    while (scanner.hasNext()) {
        String line = scanner.next();
        out.println(line.replace("),", ")," + System.lineSeparator()));
    }
    out.close();
}

The answer is simple, this line:

String line = scanner.next(); 

Should be:

String line = scanner.nextLine();

Thanks for your attempts folks sorry for being dumb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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