File Handling
File-
file is a location in a computer system where the information is stored.
Types of file-
1. System file - exe files(run by the system)
2. User file - txt,.java,.c (all user defined files)
File handling- manipulation with the file like creation, updation, deletion or etc.
Two properties of file-
1. Name
2. Extension
Works on two methods-
1. file will be created.
2. it is already existed.
How to create a file-
step 1: we have to include a package to create a file.
import java.io.File;
step 2: Create an object of File.
File f1 = new File();
step 3: pass the name of file in the parameter.
File f1 = new File("Hi.txt");
step 4: check wheather the file will be created or already existed using createNewFile().
step 5: Put the whole program inside try catch block. Inorder to catch the Exception we have to include -
import java.io.*;
(*- symbolises all utilities)
Program -
import java.io.File;
import java.io.*;
public class app
{
public static void main(String args[])
{
try
{
File fo1 = new File("Hi.txt");
if(fo1.createNewFile())
{
System.out.println("file is created");
}
else
{
System.out.println("Already exists");
}
}
catch(Exception e)
{
}
}
}
How to write in a file-
step 1: create an object of FileWriter, pass the file name in the argument.
FileWriter fo1 = new FileWriter("Hi.txt");
step 2: pass what you want to write in a file inside the write()
fo1.write("This is my first file");
step 3: After writing we have to close the Writer
fo1.close();
Program-
import java.io.File;
import java.io.*;
public class app
{
public static void main(String args[])
{
try
{
FileWriter fo1 = new FileWriter("Hi.txt");
fo1.write("This is my file");
fo1.close();
}
catch(Exception e)
{
}
}
}
How to read the file-
step 1: create an object of File.
File fo1 = new File("Hi.txt");
step 2: Create an Scanner's object.
Scanner s1 = new Scanner();
step 3: Pass the File's Object in Scanner's argument
Scanner s1 = new Scanner(fo1);
Scanner is used to read the file.
step 4: while loop is used to read till the End Of File
while()
{
}
step 5: In while loop's condition use hasNextLine()
while(s1.hasNextLine())
{
}
hasNextLine() checks the next line in the file.
step 6: Inside the while loop
while(s1.hasNextLine())
{
String data = s1.nextLine();
System.out.println(data);
}
nextLine() is used to read the data.
Comments
Post a Comment