Write a java program that writes two records of data to an output file by constr
ID: 3828475 • Letter: W
Question
Write a java program that writes two records of data to an output file by constructing a BufferedOutputStream object. Each record of data should be stored in a string with comma delimited fields that include a person’s id, name, phone, and email address. (The program should append data to an existing file or create a new file if it does not exist. No output should appear on the monitor, but a file should be created.) (10 points) 8. Write a java program that reads the records of data from the file created above and places the input into two objects.
Explanation / Answer
import java.util.*;
import java.io.*;
public class Sample1 {
public static void main(String args[]) throws IOException {
//Record 1
String name1 = "Prudhvi";
int id1 = 900619;
String phone1 = "914066132451";
String email1 = "myemail@yahuo.com";
String rec1 = name1+","+id1+","+phone1+","+email1;
//Record 2
String name2 = "Vinay";
int id2 = 902129;
String phone2 = "914097998";
String email2 = "mailers@yahuo.com";
String rec2 = name2+","+id2+","+phone2+","+email2;
String fileName = "P://file.txt";
//Reader for reading the existing data
BufferedReader br = new BufferedReader(new FileReader(new File(fileName)));
String present="";
String str;
while((str=br.readLine())!=null){
present = present+str+" ";
}
present = present+rec1+" "+rec2;
//Writer for writing the new 2 records
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(fileName)));
bw.write(present);
bw.flush();
bw.close();
}
}
File1.txt:
This is existing already
2 new records are gonna come after this
OUTPUT :
File1.txt
This is existing already
2 new records are gonna come after this
Prudhvi,900619,914066132451,myemail@yahuo.com
Vinay,902129,914097998,mailers@yahuo.com
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.