check if file exists java code example

Example 1: java create file if not exists

String yourFile = "YourFile.txt";
String yourContent = "YourContent"

File tmpDir = new File(yourFile);
boolean exists = tmpDir.exists();

if(!exists) {
	FileOutputStream fos = new FileOutputStream(yourFile);
	fos.write(yourContent.getBytes());
	fos.flush();
	fos.close();
}

Example 2: java test file exist

File tempFile = new File("c:/temp/temp.txt");
boolean exists = tempFile.exists();

Example 3: java check if file exists

import java.io.File;

File tmpDir = new File("/var/tmp");
boolean exists = tmpDir.exists();

Tags:

Java Example