user1848712
user1848712

Reputation: 105

Replacing/removing a line in a text file

public void removeLine() {
        try {
            File dir = new File("chars");
            if(dir.exists()) {
                String read;
                File files[] = dir.listFiles(); 
                for (int j = 0; j < files.length; j++) {
                    File loaded = files[j];
                    if (loaded.getName().endsWith(".txt")) {
                        Scanner s = new Scanner (loaded);
                        while (s.hasNextLine()) {
                            read = s.nextLine();
                            if (read.contains("char-15")) {
                                read.replace(read, "");
                                System.out.println(loaded.getName() +" - Data: "+read);
                                break;                          
                            }                       
                        }                   
                    }           
                }
            }
        } catch (Exception e) {

        }

    }

What this should do is replace each line that contains "char-15", with an empty String.

When I run this though, it doesn't delete the line in all the files. I can't do this manually as there are well over 5000 files.

How can I make it delete this specific line in all of the files?

Upvotes: 1

Views: 4785

Answers (4)

Tarık İNCE
Tarık İNCE

Reputation: 39

Firstly load file as String:

public static String readAllText(InputStream is) {
    StringBuilder sb = new StringBuilder();
    try {
        Reader r = new InputStreamReader(is);
        int c;
        while ((c = r.read()) != -1) sb.append(char.class.cast(c));
    } catch (Exception e) {
        //Handle Exception
    }
    return sb.toString();
}

then remove:

public static String removeUntil(String str, String c, int st)
{
    StringBuilder sb = new StringBuilder(str);
    str = sb.reverse().toString();
    for(int i = 0;i<st;i++)
        str = str.substring(0,str.lastIndexOf(c));
    sb = new StringBuilder(str);
    str = sb.reverse().toString();
    return str;
}

for ex: removeUntil("I.want.remove.this.until.third.dot",".",3); then result -> this.until.third.dot

Upvotes: 0

isvforall
isvforall

Reputation: 8926

In Java 7 you can do something like this:

if (loaded.getName().endsWith(".txt")) {
   Path path = Paths.get(loaded.getName());
   String content = new String(Files.readAllBytes(path));
   content = content.replaceAll("char-15", "");
   Files.write(path, content.getBytes());
}

Upvotes: 0

Selvaraj
Selvaraj

Reputation: 726

Java sting is immutable and final, whichever operation you made in String, it will create new instance only. So read.replace(read, ""); is not help to replace word in your file.

Upvotes: 0

Makky
Makky

Reputation: 17461

You can do this easily by using Apache Common IO API

Here is full working example

import java.io.File;
import java.io.IOException;    
import org.apache.commons.io.FileUtils;

public class FileUpdater {

    public static void main(String[] args) throws IOException {
        File dir = new File("D:\\dummy");
        if (dir.exists() && dir.isDirectory()) {
            File[] listFiles = dir.listFiles();
            for (File file : listFiles) {
                if (file.getName().contains(".txt")) {
                    String fileString = FileUtils.readFileToString(file);
                    String finalString = fileString.replaceAll("char-15", "");
                    FileUtils.writeStringToFile(file, finalString);
                }

            }
        }
    }

}

Above code will replace char-15 to empty in every file

}

Upvotes: 2

Related Questions