我有一个包含多行的文件。我的java程序必须从它读取每三行,并将它们格式化为一行并将其写入另一个文件。如何判断忽略文件中的某些行?
例如:
程序读取的文件:
首先,第二,第三
布拉斯的Blad,Blaff,
Mop,Mp,Sup
必须将这三行改为:
首先,Sup,Blaff
它是否正确,但我怎么能告诉程序忽略某些具有特定单词的行,例如,如果它有特定的单词,如其中一行中的“sub”?
代码示例如下:
public static void main(String[] args) throws Exception {
String text = "";
String changedText = "";
String first = "", second = "", third = "";
int outerCounter = 0;
int innerCounter = 0;
int arturCounter = 0;
String temp = "";
//first, we read data from file
java.io.File file = new java.io.File("test.txt");
Scanner input = new Scanner(file);
input.useDelimiter("\r");
while(input.hasNextLine()) {
text = input.next();
outerCounter += 1;
innerCounter = 0;
for (String string : text.split(",")) {
innerCounter += 1;
if(outerCounter == 1) {
second = string;
break;
}
else if(outerCounter == 2 && innerCounter == 3) {
third = string;
}
else if(outerCounter == 3 && innerCounter == 3) {
first = string;
outerCounter = 0;
second = second.replace("\n", "").replace("\r", ""); //very important part, solves the problem with new line!
changedText += second + "," + first + "," + third + "\r" + "\n";
}
}
}
//second, we write obtained data to another file
//PrintWriter creates the file
java.io.PrintWriter output = new java.io.PrintWriter("testOutput.txt");
//write formatted output to the file
output.println(changedText);
//close the file
output.close();
System.out.println(changedText);
}
}
提前感谢您的帮助。
答案 0 :(得分:-1)
我会遵循这个范例: