package Pack1;
import java.io.File;
import java.io.IOException;
public class my_file {
public static void main(String[] args) {
try {
File my_file_obj = new File("my_new_file.txt");
if (my_file_obj.createNewFile()) {
System.out.println("New File created: " + my_file_obj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("Oops some error.");
e.printStackTrace();
}
}
}Output (First Run):
New File created: my_new_file.txt
| Method | Return Type | Behavior |
|---|---|---|
createNewFile() |
boolean |
Atomically creates a new empty file if it does not exist yet (throws IOException). |
exists() |
boolean |
Returns true if the file or directory exists on disk. |
length() |
long |
Returns the file size in bytes (or 0L if the file does not exist). |
getAbsolutePath() |
String |
Returns the full resolved path from the filesystem root. |
mkdir() / mkdirs() |
boolean |
Creates a single directory (mkdir) or including missing parent folders (mkdirs). |
delete() |
boolean |
Deletes the file (or empty directory) and returns true on success. |
When you pass a relative name like new File("my_new_file.txt"), Java creates the file in your current working/project directory (e.g., C:\Users\user_name\eclipse-workspace\java_projects). For custom folders:
new File("D:\\java_files\\my_new_file.txt")new File("/Users/java_files/my_new_file.txt")System.getProperty("file.separator") (or File.separator):package Pack1;
import java.io.File;
import java.io.IOException;
public class my_file {
public static void main(String[] args) {
// Cross-platform separator ("\" on Windows, "/" on Linux/macOS):
String my_separator = System.getProperty("file.separator"); // or File.separator
String my_path = "D:" + my_separator + "java_files" + my_separator;
System.out.println("Universal Path: " + my_path + "my_new_file2.txt");
}
}Terminal Output:
Universal Path: D:/java_files/my_new_file2.txt
Note that new File(...) only represents the file path; to write text into the file, wrap FileWriter in a try (...) block so the stream is flushed and closed automatically:
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileDemo {
public static void main(String[] args) {
// try-with-resources automatically flushes and closes FileWriter!
try (FileWriter writer = new FileWriter("my_new_file.txt")) {
writer.write("Welcome to plus2net Java File Handling!\n");
writer.write("Second line of text.");
System.out.println("Successfully wrote text to my_new_file.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}Terminal Output:
Successfully wrote text to my_new_file.txt
Passing your File object to new Scanner(my_file_obj) inside a while (reader.hasNextLine()) loop reads the file line by line:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileDemo {
public static void main(String[] args) {
File my_file_obj = new File("my_new_file.txt");
try (Scanner reader = new Scanner(my_file_obj)) {
while (reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
}Terminal Output:
Welcome to plus2net Java File Handling!
Second line of text.
Before reading or deleting a file, you can inspect its attributes using exists(), canRead(), canWrite(), and length():
import java.io.File;
public class FileMetadataDemo {
public static void main(String[] args) {
File f = new File("my_new_file.txt");
if (f.exists()) {
System.out.println("File Name: " + f.getName());
System.out.println("Readable: " + f.canRead() + " | Writable: " + f.canWrite());
System.out.println("Size: " + f.length() + " bytes");
}
}
}Terminal Output:
File Name: my_new_file.txt
Readable: true | Writable: true
Size: 60 bytes
In modern Java (Java 11+), java.nio.file.Files.writeString() and Files.readString() read and write UTF-8 text files in a single line:
import java.nio.file.Files;
import java.nio.file.Path;
public class ModernNioFileDemo {
public static void main(String[] args) throws Exception {
Path p = Path.of("nio_sample.txt");
Files.writeString(p, "One-line write & read with java.nio.file.Files!");
System.out.println(Files.readString(p));
Files.deleteIfExists(p);
}
}Terminal Output:
One-line write & read with java.nio.file.Files!
| Feature | java.io.File |
java.nio.file.Path & Files |
|---|---|---|
| Error Reporting | Returns false silently on delete() |
Throws descriptive IOException on failure |
| One-Line Text Read/Write | Requires FileWriter / Scanner |
Built-in (Files.readString / writeString) |
| Symbolic Links & Copy | Limited support | Full support (Files.copy(), Files.move()) |
In Java string literals,
is interpreted as a newline character and as a tab! Writing new File("D:
ew_file.txt") corrupts the filename. Always escape backslashes as "D:\\new_file.txt", use forward slashes "D:/new_file.txt" (which Java supports on Windows too!), or use File.separator.
my_file_obj.createNewFile() throws an IOException if the parent directory (such as D:\java_files) does not exist yet! Call my_file_obj.getParentFile().mkdirs(); before calling createNewFile().
import java.io.File;
import java.io.FileWriter;
public class FileHandlingFullDemo {
public static void main(String[] args) throws Exception {
File temp = new File("test_verify.txt");
try (FileWriter fw = new FileWriter(temp)) {
fw.write("plus2net");
}
if (temp.exists() && temp.length() == 8 && temp.delete()) {
System.out.println("All Java File create, write, length & delete checks passed!");
}
}
}Terminal Output:
All Java File create, write, length & delete checks passed!
No! The new File(...) constructor only creates an in-memory path object. The actual file is created on disk only when you call createNewFile() or open a FileWriter / FileOutputStream.
Pass true as the second argument to the FileWriter constructor: new FileWriter("my_new_file.txt", true).
No, createNewFile() is safe: if the file already exists, it leaves the existing file untouched and simply returns false.
In Java, File.delete() can only delete a directory if the directory is completely empty. You must delete all files inside the folder first.
Call my_file_obj.toPath() to convert a File to a Path, or myPath.toFile() to convert a Path back to a File.
java.util.Scanner to parse tokens and lines.AutoCloseable.InputStream and Reader.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.