Categories
unix

Deleting blank lines in a file using UNIX

In this post, let us learn about deleting blank lines in a file using UNIX.

Creating File with blank lines

I am having one file with the following as the content and also some blank/empty lines in it.

cat abc.txt
apple
Mango
Orange

Grapes

Peer

Pineapple

Using the below-given command, we can get to know the count of the line which includes the blank lines also.

wc -l abc.txt
9 abc.txt

This command lists the number of blank lines in a file.

^ – beginning of the line

$ – ending of the line

grep -c ^$ abc.txt
3

sed command helps us to delete the empty lines by checking for the matches.

sed -i '/^$/d' abc.txt

After the deletion, the File in the UNIX looks like below.

cat abc.txt
apple
Mango
Orange
Grapes
Peer
Pineapple

The count of the file after deleting the blank lines in a file using UNIX.

cat abc.txt |wc -l
6

Categories
file java

delete a file from java code

In this post, we will learn to delete a file from java code.

When you are delete a file from java. It will delete the file permanently. It will not moved to Trash or Recycle bin

Before executing this code, please make sure you have delete permission for that file from java.
Else you will get Permission denied Exception

Syntax
boolean isDeleted = file.delete();
Example
import java.io.File;

public class DeleteFileExample {

	public static void main(String[] args) {
		try {
			File file = new File("C:\\sample.txt");
			// Below if condition will check that file exists or not
			if (file.exists()) {
				boolean isDeleted = file.delete();
				if (isDeleted == true) {
					System.out.println("File deleted Successfully");
				} else {
					System.out.println("Not able to delete the file");
				}
			} else {
				System.err.println("File path is not correct");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
File deleted Successfully
File delete using nio pacakage

In Above example, we can customize our exceptions like file not found, file delete staus.

Below example is quick way of deleting file, But we cannot customize out exception

Syntax
	Files.deleteIfExists(Paths.get("C://temp//sample.txt"));
Example
import java.nio.file.Files;
import java.nio.file.Paths;

public class DeleteFileExample {

	public static void main(String[] args) {
		try {
			// Below line will delete if the file exist
			Files.deleteIfExists(Paths.get("C://temp//sample.txt"));
			System.out.println("File deleted successfully");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
File deleted successfully
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/files/DeleteFileExample.java

Related Articles

how to list all files inside a folder using java

how to read a file from java with example