JAVA Below is a source code for writing a formatted text in a text (.txt) file.
ID: 3875365 • Letter: J
Question
JAVA
Below is a source code for writing a formatted text in a text (.txt) file. Examine the code and answer the below questions;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String owner = "Jane";
File myfile = new File("inventory.txt");
if (!myfile.exists()){
myfile.createNewFile();
}
FileWriter toFile = new FileWriter(myfile);
PrintWriter print = new PrintWriter(toFile);
print.printf("This is %s's laptop", owner);
toFile.close();
}
}
Using Scanner, write a method to give a user the flexibility to enter and use different text (.txt) files whenever using the program.
Assume the text file has more than one line of texts, write a method that reads from the file created in the source code and displays only the line with a specified text.
Explanation / Answer
import java.io.*;
import java.util.Scanner;
public class Main {
//insert File using scanner
public String insertFileName(){
Scanner sc = new Scanner(System.in);
System.err.println("Enter a file name without extension");
String name = sc.next();
sc.close();
return name+".txt";
}
//firest read from file then display it line by line
public void readDisplayFile(String filename){
try {
FileInputStream fstream = new FileInputStream(filename);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
}
catch(Exception e){
System.out.println("No file exist with this name");
}
}
public static void main(String[] args) throws IOException {
String owner = "Jane";
Main main = new Main();
String fileName = main.insertFileName();
//create file using given file name
File myfile = new File(fileName);
if (!myfile.exists()){
myfile.createNewFile();
}
FileWriter toFile = new FileWriter(myfile);
PrintWriter print = new PrintWriter(toFile);
print.printf("This is %s's laptop", owner);
toFile.close();
main.readDisplayFile(fileName);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.