[英]remove only matching word from file in java
Hi i have a file contain some word , my requirement is to remove the matching word.If word is remove from between the line rest of the word below has to shifted up to avoid white space. 嗨,我有一个包含一些单词的文件,我的要求是删除匹配的单词。如果单词从下面单词的其余行之间删除,则必须向上移动以避免空格。
File.txt
medical_data01
medical_data02
medical_data
Census_data_10000_k.gen
Census_data_10000_k.gen_01
Census_data_10000_k.gen_02
If i remove medical_data
Output should come like this 如果我删除了
medical_data
输出应该是这样的
medical_data01
medical_data02
Census_data_10000_k.gen
Census_data_10000_k.gen_01
Census_data_10000_k.gen_02
But my code output is coming like this 但是我的代码输出是这样的
01
02
Census_data_10000_k.gen
Census_data_10000_k.gen_01
Census_data_10000_k.gen_02
File file = new File(
RESOURCE_BUNDLE.getString("tested"));
File temp = File.createTempFile("file", ".txt",
file.getParentFile());
String charset = "UTF-8";
String delete = "medical_data";
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(file),
charset));
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(new FileOutputStream(temp),
charset));
String currentLine;
while ((currentLine = reader.readLine()) != null) {
currentLine = currentLine.replace(delete,"");
if (currentLine.equals("")) {
} else
writer.println(currentLine);
}
writer.close();
reader.close();
file.delete();
temp.renameTo(file);
While your code is quite ugly it should work. 虽然您的代码很丑陋,但它应该可以工作。
The only problem I can see would be a suboptimal block management. 我能看到的唯一问题将是次优的块管理。 Also you are missing a trim() to cut lines consisting of only whitespaces.
另外,您缺少trim()来剪切仅包含空格的行。 Try this instead:
尝试以下方法:
while ((currentLine = reader.readLine()) != null) {
currentLine = currentLine.replace(delete,"").trim();
if (!currentLine.isEmpty()) {
writer.println(currentLine);
}
}
To remove only 'medical_data' you need to change this code: 要仅删除“ medical_data”,您需要更改以下代码:
while ((currentLine = reader.readLine()) != null) {
currentLine = currentLine.replace(delete,"");
if (currentLine.equals("")) {
} else
writer.println(currentLine);
}
to this code: 此代码:
while ((currentLine = reader.readLine()) != null) {
if (!currentLine.equals(delete)) {
writer.println(currentLine);
}
}
Then the output file looks like this: 然后,输出文件如下所示:
medical_data01
medical_data02
Census_data_10000_k.gen
Census_data_10000_k.gen_01
Census_data_10000_k.gen_02
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.