So I'm trying to read input from a text file, store it into variables, and then output an altered version of that text onto a different file using a variable from the file. I'm using Filereader, Scanner, and Printwriter to do this. I have to store the last line (which is a number) from this text document and use that number to multiply the body of text onto a different file without including the number.
So the text is: Original file text
And the output is SUPPOSED to be: desired output
I'm able to retrieve the number and store it into my multiplier variable and retrieve the text into my string BUT it's stored as a single line if I check inside the console: how the text is stored seen through console
so it outputs like this on the new file: undesired output
I'm pretty new to Java, forgive me if there are any questions I can't answer that could help solve any issues with my code.
I've tried adding +"n"
to the file output line but no dice. I've also tried adding it to words += keys.nextLine() +"n"
, and it separates the lines in the CONSOLE but not the file itself, unfortunately. Am I at least on the right track?
Here's my code:
public class fileRead {
public static void main(String[] args) throws IOException{
String words = "" ; //Stores the text from file
int multiplier = 1; // Stores the number
FileReader fr = new FileReader("hw3q3.txt");
Scanner keys = new Scanner(fr);
//while loop returns true if there is another line of text will repeat and store lines of text until the last line which is an int
while(keys.hasNextLine())
if (keys.hasNextInt()) { //validation that will read lines until it see's an integer and stores that number
multiplier = keys.nextInt(); //Stores the number from text
} else {
words += keys.nextLine();//Stores the lines of text
keys.nextLine();
}
keys.close();
PrintWriter outputFile = new PrintWriter("hw3q3x3.txt");
for(int i = 1; i <= multiplier; i++) {
outputFile.println(words);
}
outputFile.close();
System.out.println("Data Written");
System.out.println(multiplier);//just to see if it read the number
System.out.println(words); //too see what was stored in 'words'
}
}