Creating a java program to implement stepwise refinement. It is supposed to upda
ID: 647177 • Letter: C
Question
Creating a java program to implement stepwise refinement. It is supposed to update the sequential master text file containing names: Abel, Brown, Harris, James, Jones, Smith, Townsend. There are three types
of transactions: insertions, modifi cations, and deletions, with transaction codes 1, 2,
and 3, respectively. The transaction types are
Type 1: INSERT (a new subscriber into the master file)
Type 2: MODIFY (an existing record)
Type 3: DELETE (an existing record)
Transactions are sorted into alphabetical order by name. If more than
one transaction is performed for a given name, the transactions for that name
are sorted so that insertions occur before modifi cations and modifi cations before
deletions.
Explanation / Answer
import java.util.*;
import java.util.Scanner;
public class Master{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1.insertion into file 2.modify into file 3.delete in file");
int choice=sc.nextInt();
File newTextFile = new File("masterfile.txt");
File temp = File.createTempFile("duplicateMaster", ".txt", file.getParentFile());
String charset = "UTF-8";
if(choice==1){
System.out.println("Enter String to insert");
String str = sc.nextLine();
FileWriter fw = new FileWriter(newTextFile);
fw.write(str);
fw.close();
}
if(choice==2){
Path path = Paths.get("masterfile.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
System.out.println("Enter String you want to modify which is present in text file");
String input = sc.nextLine();
System.out.println("Enter new modified string");
String output = sc.nextLine();
content = content.replaceAll(input, output);
}
if(choice==3){
String delete = "foo";
System.out.println("Enter string to delete");
String delete = sc.nextLine();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
for (String line; (line = reader.readLine()) != null;) {
line = line.replace(delete, "");
writer.println(line);
reader.close();
writer.close();
file.delete();
temp.renameTo(file);
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.