2

I am currently reading a .txt file from my computer using this code:

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] == "yes")) {
            file.add(data);
        } else {
            //Remove line here  
        }
    }
} finally {
    in.close();
}

Now for every line I read I do a simple if check, if the answer is not "yes" I want to delete the line and continue to the next one.

Is this possible? Or can you only read and not change?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user2911924
  • 331
  • 3
  • 5
  • 15

4 Answers4

4

You can not "delete" a specific line from a file, but you can read the lines, remove the unwanted and overwrite the file content with the cleaned lines.

Smutje
  • 17,733
  • 4
  • 24
  • 41
0

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());
giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
0

The simplest solution is to copy all the lines you want to keep and replace the existing file with the one you just created.

File orig = new File("Data/text.txt");
File tmp = new File(orig+".tmp");
try (BufferedReader in = new BufferedReader(new FileReader(orig));
     PrintWriter pw = new PrintWriter(new FileWriter(tmp))) {
     for (String data; (data = in.readLine()) != null; )
          if (data.split(":")[1].equals("yes"))
              pw.println(data);
}
if (orig.delete())
    tmp.renameTo(orig);
else
    // cannot delete old file :|
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Correct me if I'm wrong, but that code of yours already 'delete' unwanted line (args[1] != "yes"), why? Because that IF of yours has a statement like:

IF 'args[1]' is 'yes' THEN add it to 'file' ELSE do nothing

That says, other than yes then it won't be added to file, you should you check file's content (I assume it's a List<String> type), but I'm pretty sure that your code is already correct as it is.

Or you can add continue; in that else block.

A-SM
  • 882
  • 2
  • 6
  • 18