Answer each of the following questions: 1. Write the code segment that does the
ID: 3690232 • Letter: A
Question
Answer each of the following questions:
1. Write the code segment that does the following: opens a file named MyName.txt, writes your first name to the file, and then closes the file.
2. Write the code segment that does the following: opens a file named MyName.txt, reads the first line from the file and displays it, and then closes the file.
3. Assume that the MyName.txt file is currently closed. Write the code segment that opens the file without erasing it, write another name to the file so that it is appended to the end of the file’s existing data, and close the file.
Explanation / Answer
Question 1
FileWrite.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileWrite {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("MyName.txt");
FileWriter writer = new FileWriter(file);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first name");
String firstName = scan.next();
writer.write(firstName);
writer.close();
System.out.println("firstName.txt file generated successfully");
}
}
Output:
Please enter your first name
Suresh
MyName.txt file generated successfully
Question 2
FileRead.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileRead {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("MyName.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String firstLine = br.readLine();
System.out.println(firstLine);
br.close();
}
}
Output:
Suresh
Question 3
FileAppend.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileAppend {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("MyName.txt");
FileWriter writer = new FileWriter(file, true);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first name");
String firstName = scan.next();
writer.write(firstName);
writer.close();
System.out.println("firstName.txt file generated with appended string successfully");
}
}
Output:
Please enter your first name
Sekhar
MyName.txt file generated with appended string successfully