[英]How can I split a string by on empty lines by using split in java?
[英]How Can I Split a Long String Into Lines At “),”?
尝试正确解析文本文件时有些头疼,这是从mysql数据库中提取出来的,但是在重新插入数据之前,需要对数据进行一些合理的更改。
我的程序正在获取一个.txt文件,并对其进行解析以生成一个.txt文件,这很简单。
问题是它没有正确分割文件。 该文件如下所示(每个中间字段看起来都很奇怪,因为我已将其更改为随机字母以隐藏真实数据):
(92,'xxxname',4013),(93,'sss-xxx',4047),(94,'xxx-sss',3841),(95,'ssss',2593),(96,'ssss-sss',2587),(97,'Bes-sss',2589),
我想将其拆分,以便生成如下文件:
(92, 'xxxname',4013),
(93, 'sss-xxx', 4047),
(94, 'xxx-sss', 3841),
等等...
当前的解析代码如下:
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();
}
目前,我得到的输出大致上正常,但拆分得比预期的要多,当然split方法将删除“)”,这是不必要的。
当前输出样本:
*(1,'Vdddd
Cfffff',1989
(2,'Wdd',3710
(3,'Wfffff
Hffffff
Limited-TLC',3901
(4,'ffffffun88',2714
(5,'ffffff8',1135
(6,'gfgg8*
在这里玩了一段时间,并在这里和其他地方做了很多搜索,但是出于想法的考虑,我们将不胜感激。
您可以使用String.replace
。 也无需创建多个PrintWriter
并每次都关闭流。
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();
}
答案很简单,这一行:
String line = scanner.next();
应该:
String line = scanner.nextLine();
感谢您的尝试,乡亲们对您的愚蠢表示歉意
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.