Modify the content of a file using Java

I would start with closing reader, and flushing writer: public class FileReplace { List<String> lines = new ArrayList<String>(); String line = null; public void doIt() { try { File f1 = new File(“d:/new folder/t1.htm”); FileReader fr = new FileReader(f1); BufferedReader br = new BufferedReader(fr); while ((line = br.readLine()) != null) { if (line.contains(“java”)) line = … Read more

PrintWriter vs FileWriter in Java

According to coderanch.com, if we combine the answers we get: FileWriter is the character representation of IO. That means it can be used to write characters. Internally FileWriter would use the default character set of the underlying OS and convert the characters to bytes and write it to the disk. PrintWriter & FileWriter. Similarities Both … Read more

Create a new line in Java’s FileWriter

If you want to get new line characters used in current OS like \r\n for Windows, you can get them by System.getProperty(“line.separator”); since Java7 System.lineSeparator() or as mentioned by Stewart generate them via String.format(“%n”); You can also use PrintStream and its println method which will add OS dependent line separator at the end of your … Read more