Answered step by step
Verified Expert Solution
Question
1 Approved Answer
To write to a file: 1- import java.io.*; 2- We need to handle the exception (try... catch) 3- Create File object to prepare the file
To write to a file: 1- import java.io.*; 2- We need to handle the exception (try... catch) 3- Create File object to prepare the file creation 4- Create PrintWriter object to write in the file 5- Use println to write in the file 6- Close the file import java.io.*; public static void main(String[] args) { Example try { File file_name= new File ("test_file.txt"); PrintWriter outputFile = new PrintWriter (file_name); outputFile.println (You are Good students"); outputFile.close(); } catch (IOException ex) { System.out.println("File not exsist"); } } To read from a file: 1- import java.io.*; 2- We need to handle the exception (try... catch) 3- Create File object to prepare the file creation 4- Create Scanner object to read from a file 5- Use nextLine to read from the file import java.io.*; 6- Close the file public static void main(String[] args) { Example try { File read_file = new File("test_file.txt"); Scanner inputFile = new Scanner(read_file); while (inputFile.hasNext()) { String str = inputFile.nextLine(); System.out.println(str); } inputFile.close(); } catch (IOException ex) { System.out.println("File not exsist"); }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started