Reputation: 93
Hi I Posted a similar question yesterday, but now I need help with reading the file name as a string variable. Attached is my updated code
import java.io.*;
import java.util.*;
public class SongWriter {
public static void main(String[] args) {
PrintWriter outputStream = null;
// Scope must be outside the try/catch structure.
String fileName1;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of the file. The file should end in the suffix.txt ");
fileName1 = keyboard.next();
try {
outputStream = new PrintWriter("Song.txt");
// new FileOutputStream("Song.txt")
} catch (FileNotFoundException e) {
System.out.println("Error opening the file Song.txt.");
System.exit(0);
}
System.out.println("\n classical songs has many lines");
System.out.println("\nNow enter the three lines of your Song.");
String line = null;
//Scanner keyboard = new Scanner(System.in);
int count;
for (count = 1; count <= 3; count++) {
System.out.println("\nEnter line " + count + ": ");
line = keyboard.nextLine();
outputStream.println(count + "\t" + line);
}
outputStream.close();
System.out.println("\nYour Song has been written to the file song.txt.\n");
} // end of main
} // end of class
My initial question was how do I Adjust the program so it first asks for a name of the file to write to. Use the Scanner class and its next() method. Read in the file name as a string variable after informing the reader the file name should end in the suffix .txt Eg:- Song with the file names Song1.txt,Song2.txt and Song3.txt. With the help of others I was able to have the scanner class and the next() in my code. Can someone please tell me why my code is not working?
Upvotes: 0
Views: 2255
Reputation: 201447
Change this line
// Use "Song.txt"
outputStream = new PrintWriter("Song.txt");
to
// Use the value stored in the fileName1 String.
outputStream = new PrintWriter(fileName1);
Also, you're not getting the entire line with keyboard.next()
you should something like this instead
fileName1 = keyboard.nextLine().trim();
Upvotes: 1