Java PrintWriter not working

Close your PrintWriter in a finally block to flush it and to reclaim resources public void writeToFile(String fileName) { // **** Note that pW must be declared before the try block PrintWriter pW = null; try { pW = new PrintWriter(new File(fileName)); for (int x = 0; x < 25; x++) { for (int y … 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

Java – delete line from text file by overwriting while reading it

As others have pointed out, you might be better off using a temporary file, if there’s a slightest risk that your program crashes mid way: public static void removeNthLine(String f, int toRemove) throws IOException { File tmp = File.createTempFile(“tmp”, “”); BufferedReader br = new BufferedReader(new FileReader(f)); BufferedWriter bw = new BufferedWriter(new FileWriter(tmp)); for (int i … Read more

PrintWriter append method not appending

The fact that PrintWriter‘s method is called append() doesn’t mean that it changes mode of the file being opened. You need to open file in append mode as well: PrintWriter pw = new PrintWriter(new FileOutputStream( new File(“persons.txt”), true /* append = true */)); Also note that file will be written in system default encoding. It’s … Read more