As already been said you can read all the lines and skip the ones don't want, after that you can store the rest of them in the same file.
List<String> file = new ArrayList();
BufferedReader in = new BufferedReader(new FileReader("./Data/text.txt"));
String data = null;
try {
while ((data = in.readLine()) != null) {
String[] args = data.split(":");
if (args[1].equals("yes")) {
file.add(data);
} else {
//skip this line
}
}
in.close();
//Add to file
FileWriter fw = new FileWriter("./Data/text.txt");
BufferedWriter out = new BufferedWriter(fw);
for (String line : file) {
out.write(line + "\n");
}
out.flush();
out.close();
} catch (Exception e){
}
You can also use Apache Commons IO.
File file = new File("./Data/text.txt");
List<String> lines = org.apache.commons.io.FileUtils.readLines(file)
for (int i = 0; i < lines.size(); i++)
if (! lines.get(i).split(":")[1].equals("yes"))
lines.remove(i--);
org.apache.commons.io.FileUtils.writeLines(file, lines);
You must be very careful with arg[1]
if you have an empty line the result would be an ArrayIndexOutOfBoundsException
.
Addendum
I'd like to post another way using Java 8 lambda expressions and Java 7 java.nio.file.*
package.
List<String> lines = Files.readAllLines(Paths.get("./Data/text.txt"), Charset.defaultCharset());
Predicate<String> filter = line -> line.split(":")[1].equals("./Data/text.txt");
String output = lines
.stream()
.filter(filter)
.map(l -> l + "\n")
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
Files.write(Paths.get("test"), output.getBytes());