Files in Java (2)
Files in Java (2)
To use the File class, create an object of the class, and specify the filename or directory name:
Example:
import java.io.File; // Import the File class
File myObj = new File("filename.txt"); // Specify the filename
Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a
boolean value: true if the file was successfully created, and false if the file already exists. Note
that the method is enclosed in a try...catch block. This is necessary because it throws an
IOException if an error occurs (if the file cannot be created for some reason):
Read a file
In the following example, we use the Scanner class to read the contents of the text file we
created in the previous Example:
Output:
C:\Users\ria\Java\Files>javac GetFileInfo.java
C:\Users\ria\Java\Files>java GetFileInfo
File name: filename.txt
Absolute path: C:\Users\ria\Java\Files\filename.txt
Writeable: true
Readable true
File size in bytes 52
=======================================================
Unlike FileOutputStream class, you don't need to convert string into byte array because
it provides a method to write string directly.
Constructors of FileWriter
class
Constructor Description
Creates a new file. It gets file name in
FileWriter(String file) string.
Creates a new file. It gets file name in File
FileWriter(File file) object.
Methods of FileWriter class
Method Description
void write(String text) It is used to write the string into FileWriter.
void write(char c) It is used to write the char into FileWriter.
void write(char[] c) It is used to write char array into FileWriter.
void flush() It is used to flushes the data of FileWriter.
void close() It is used to close the FileWriter.
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}