I am creating a program in Java that Scans a text file and one of the requiremen
ID: 3637657 • Letter: I
Question
I am creating a program in Java that Scans a text file and one of the requirements of this program is to allow the user to input an output file name using PrintStream. I don't know how/where to add the PrintStream class so that it allows the user to choose a file name.Here is what I have so far:
import java.util.*;
import java.io.*;
public class HealthFile {
/**
* @param args
*/
public static void main(String[] args) {
// Creates the Scanner
Scanner s = new Scanner(System.in);
String filename ="test.txt";
try
{
s = new Scanner(new FileReader(filename));
}
catch (Exception e)
{
System.out.printf("ERROR: File NOT found");
// Can end the program or do something else here…
}
System.out.printf("%-20s%15s ", "Last Name ", "Date of Birth");
while (s.hasNext()) {
String firstname;
firstname = s.next();
String lastname;
lastname = s.next();
int id;
id = s.nextInt();
String dateofbirth;
dateofbirth= s.next();
System.out.printf("%-20s%15s ", lastname, dateofbirth);
}
s.close();
Explanation / Answer
PrintStream itself cannot handle any input, however, it can take in a String containing a filename that CAN be printed. For example, you can add the following to your code: System.out.print("Please enter a file to write to: "); try{ BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); String fileName = bufferRead.readLine(); PrintStream printStream = new PrintStream(fileName); } catch(IOException e) { System.out.println("Error: "+e.getMessage()); } BufferedReader takes the file from the user and passes it into PrintStream, so if a user passes in "test.txt", a file called test.txt will be created in the same directory as the class file for you to use.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.