OOP's (CS3391)
OOP's (CS3391)
Reading and
Writing Files
To create a file in Java, you
can use the createNewFile()
method. This method
returns a boolean value: true
1) Create a File if the file was successfully
created, and false if the file
already exists.
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " +
myObj.getName());
Eg program } else {
System.out.println("File already exists.");
to CREATE }
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
SS 1.1 JAVA program to create the file is COMPILED
SS 1.2 New File has been created
In the following example,
we use the FileWriter class
together with its write()
method to write some text to
the file we created in the
2) Write a File example above. Note that
when we are done writing to
the file, we should close it
with the close() method
import java.io.FileWriter;
import java.io.IOException;
Eg program IV");
myWriter.close();
Eg program System.out.println(data);
}
to READ myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
SS 3.1 Program to Read the written File
SS 3.2 The file has been read successfully
Thankyou!
do you have any questions?