Part a ** in Java Consider a text file of the following form, Dennis M Ritchie B
ID: 3697614 • Letter: P
Question
Part a ** in Java
Consider a text file of the following form,
Dennis M Ritchie
Bill H Gates
Steve P Jobs
Ira F Pohl ...
Your goal is to write a small class to read in this data and echo each name back to the command line. Assume this input file is named “names.txt”. Within your main method, write the code to open the file, read in the data, and echo each name in its entirety to the command line. After reaching the end of the file, remember to close the input file
Part b
In the last exercise, we saw how we could read from a file. Now we’ll write some code to write to a file. For this program, write the java code to create a file called ‘people.txt’. Within this file, you’ll write a few names along with the person’s age and birth month (You can make up names/ages here). The format of the file should be as such,
John Smith 90 August
Wilber Jones 45 July
Jolene Carter 35 October ...
How will you go about writing in this fashion? Certainly, there are many strategies you can use. Experiment with the differences between print and println here. Remember to close the file once you have finished writing.
Explanation / Answer
Please follow the code and comments for description :
CODE :
a)
package questions;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReader {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("names.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
OUTPUT :
Dennis M Ritchie
Bill H Gates
Steve P Jobs
Ira F Pohl ..
b)
package questions;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileWriter {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
FileWriter fw = new FileWriter("people.txt", true);
System.out.println("Enter the name : ");
String s = sc.nextLine();
fw.write(s);
fw.write(" ");
System.out.println("Enter the Age : ");
String a = sc.nextLine();
fw.write(a);
fw.write(" ");
System.out.println("Enter the birth month :");
String b = sc.nextLine();
fw.write(b);
fw.write(" ");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
OUTPUT :
The below is the data written to the file.
John 28 June
Abraham 59 August
Saif 52 January
John Smith 90 August
Hope this is helpful.