File Handling in Java
File Handling in Java
Stream
Import statements
• import java.io.FileInputStream;
• import java.io.FileOutputStream;
• import java.io.IOException;
throws IOException
Closing the streams
• Whether or not error occurs
Return type of read method – int
• Value bytes is returned as int in the range 0 to 255
• -1 on reaching EOF
When used?
Import statements
• import java.io.FileReader;
• import java.io.FileWriter;
• import java.io.IOException;
throws IOException
Closing the streams
• Whether or not error occurs
Return type of read method – int
• Stores value in last 16 bits
• -1 on reaching EOF
try {
inputStream = new BufferedReader(new FileReader("myfile.txt"));
outputStream = new PrintWriter(new FileWriter("myfile1.txt"));
String str;
while ((str = inputStream.readLine()) != null) {
outputStream.println(str);
}
} finally {
*****Handle IOException
File obj1 = new File(“myfile.txt”);
if (obj1.exists())
{
System.out.println("File name: " + obj1.getName());
System.out.println("Absolute path: " + obj1.getAbsolutePath());
System.out.println("Writeable: " + obj1.canWrite());
System.out.println("Readable " + obj1.canRead());
System.out.println("File size in bytes " + obj1.length());
}
else
{
System.out.println("The file does not exist.");
}
public static void main(String[] args)
{
try {
File myObj = new File("myfile.txt");
Scanner r1 = new Scanner(myObj);
while (r1.hasNextLine())
{
String data = r1.nextLine();
System.out.println(data);
}
r1.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}