Categories
file java

get the last modified date of a file in Java

In this post, we will learn about get the last modified date of a file in Java

It returns the value in long format,

we need to use SimpleDateFormat to convert into date format

Syntax
file.lastModified();
Example

import java.io.File;
import java.text.SimpleDateFormat;

public class LastModifedDate {

	public static void main(String[] args) {
		try {
			File file = new File("C:\\Project.log");
		
			if (file.exists()) {
				long lastModified = file.lastModified();

				SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
				System.out.println(sdf.format(lastModified));

			} else {
				System.err.println("File path is not correct ");
			}

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

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

Related Articles

how to read a file from java with example

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

Categories
file java

how to list all files inside a folder using java

In this post, we will how to list all files inside a folder using java. Here we will use File.java for these operations

In below example we are going to use .list method to list all files and directories without trans versing into sub directories.

The file path I am going to use is F:\Java which having file like below image 

Example
import java.io.File;

public class ListAllFilesExample {

	public static void main(String[] args) {
		try {

			File file = new File("F:\\Java");
			String[] list = file.list();
			for (String fileName : list) {
				System.out.println(fileName);
			}

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

}

Output

access.txt
apache-tomcat-8.5.35
eclipse
Maven
sample.txt
sts-bundle
Transverse into sub folders using Java 8

Using java8 we can easily transverse into all sub folders in side the folder. In below Example we are using Files.walk to get all the files and folders by trans versing inside the folders

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ListAllFilesUsingJava8 {

	public static void main(String[] args) {
		try {
			Path path = Paths.get("F:/Java");
			Stream<Path> walk = Files.walk(path);
			walk.forEach(x -> System.out.println(x.getFileName()));

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

	}

}
Output
org.eclipse.datatools.enablement.hsqldb.ui_1.2.1.201712071719.jar
org.eclipse.datatools.enablement.hsqldb_1.2.1.201712071719.jar
org.eclipse.datatools.enablement.ibm.db2.iseries.dbdefinition_1.2.1.201712071719.jar
Github

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

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

Related Articles

how to read a file from java with example

create text file from java with example

Categories
file java

how to read a file from java with example

In this post, we will learn about how to read a file from java with example

This will called as IO operations

There are many ways to read a file from java. BufferedReader, Scanner, Streams

BufferReader

BufferReader is one of the common way to read a file from java. It will read the file line by line

It is synchronized, so the operations will be thread safe

Once the read operation is done we need to close the BufferReader

we are getting chance of IOException in this code, so we should surround the code by try catch

Example

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class ReadFileExample {

	public static void main(String[] args) {
		try {
			
			File file = new File("C://temp/sample.txt");
			FileInputStream fileInputStream = new FileInputStream(file);
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
			
			// Converting input stream to buffer reader
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String temp = "";
			StringBuffer textFileContent = new StringBuffer();
			while ((temp = bufferedReader.readLine()) != null) {
				textFileContent.append(temp);
			}
			
			System.out.println(textFileContent);
			// In below line we are closing the bufferReader
			bufferedReader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Output
sdfdsfdsfsdfsHelloworld
Scanner

In this example we will do the same operation using Scanner. Here are also we used while loop to iterate the content of file as like bufferedReader

Once we done with the operation we nee to close the scanner as like BufferReader

Scanner Example

import java.io.File;
import java.util.Scanner;

public class ReadFileScannerExample {

	public static void main(String[] args) {
		try {
			File file = new File("C:\\temp\\sample.txt");
			
			Scanner scanner = new Scanner(file);
			StringBuffer textFileContent = new StringBuffer();
			while (scanner.hasNextLine()) {
				textFileContent.append(scanner.nextLine());
			}
			System.out.println(textFileContent);
			scanner.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
sdfdsfdsfsdfsHelloworld
Using NIO pacakge

Using NIO package we have Files.ReadAllBytes method. Using this we can read file as byte array. Then we can convert this into a string as like below example

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Sample {

	public static void main(String[] args) throws IOException {
		byte[] encoded = Files.readAllBytes(Paths.get("D:\\workspace\\sample.txt"));
		String s = new String(encoded, StandardCharsets.US_ASCII);
		System.out.println(s);
	}
}
java.io.FileNotFoundException

If java not able to find the file it will throw the below exception

java.io.FileNotFoundException: C:\temp\sample.txt1 (The system cannot find the file specified)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.util.Scanner.<init>(Scanner.java:611)
	at com.geeks.example.ReadFileScannerExample.main(ReadFileScannerExample.java:12)
Github

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

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

Related Articles

create text file from java with example

Categories
file java

create text file from java with example

In this post, we are going to learn create text file from java with example

In this example, we are going to use File.java to create file

please make sure your code is under try catch block. Because there is chance to getting IOException

Prerequisites
  • Java installed
  • your program should have access to create file on the path
Syntax
	file.createNewFile();
Example
import java.io.File;

public class CreateFileExample {

	public static void main(String[] args) {
		try {
			File file = new File("C://temp//sample.txt");
			// .exists Method check if file already exists on the path
			if (!file.exists()) {
				// Below line will create file sample.txt on C://temp// folder
				file.createNewFile();
				System.out.println("File created succesfully !!");
			} else {

				System.err.println("File already exists");
			}

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

}
Output
File created succesfully !!

if file already exists in the C://temp folder we will get below output

File already exists
Access denied

Make sure you have access from java to create file on the folder else you will get access denied exception like below

java.io.IOException: Access is denied
	at java.io.WinNTFileSystem.createFileExclusively(Native Method)
	at java.io.File.createNewFile(File.java:1012)
	at com.geeks.example.CreateFileEaxmple.main(CreateFileEaxmple.java:11)
Github

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

Related Articles

how to read a file from java with example