So I've got the basic code for this however due to the while loop I'm using, I can really only write the last line of the text file to the new file. I'm trying to modify the text from testfile.txt
and write it to a new file named mdemarco.txt
. The modification I'm trying to do is add a line number in front of each line. Does anybody know a way to maybe write the contents of the while loop to a string while it runs and output the resulting string to mdemarco.txt
or anything like that?
public class Writefile
{
public static void main(String[] args) throws IOException
{
try
{
Scanner file = new Scanner(new File("testfile.txt"));
File output = new File("mdemarco.txt");
String s = "";
String b = "";
int n = 0;
while(file.hasNext())
{
s = file.nextLine();
n++;
System.out.println(n+". "+s);
b = (n+". "+s);
}//end while
PrintWriter printer = new PrintWriter(output);
printer.println(b);
printer.close();
}//end try
catch(FileNotFoundException fnfe)
{
System.out.println("Was not able to locate testfile.txt.");
}
}//end main
}//end class
The input file text is:
do
re
me
fa
so
la
te
do
And the output I'm getting is only
8. do
Can anybody help?
Change it to
b += (n+". "+s);
.Try this:
instead of:
and
instead of:
Your content on each line of text didn't saved. So only the last line displays on the output file. Please try this:
The
String
variableb
is overwriten in each iteration of the loop. You want to append to it instead of overwriting (you may also want to add a newline character at the end):Better yet, use a
StringBuilder
to append the output: