Reputation: 21
I am trying to print to a file while printing to the monitor at the same time. By the way, it prints to the monitor perfectly fine. My code doesn't even create the file. That is very confusing because I created a file in other parts of my code and it worked fine.
I am aware that there is a solution to a problem similar to mine however, I havent learned about FileOutputStream or PrintStream. I am in a intro to coding class and we can only use what was taught in class. Is there another way to accomplish this?
Below is my code.
public static void printLine(char n, int count) throws IOException //prints lines of chord
{
FileWriter file = new FileWriter("outFile.txt",true);
PrintWriter outputfile = new PrintWriter(file);
//File outFile = new File("outFile.txt");
char[] lineNames = {'f','d','B','G','E','C'};
char[] spaceNames = {'e','c','A','F','D'};
char[] lineAr = {'-','-',n,'-','-'}; //array to print lines
char[] spaceAr = {' ',' ',n,' ',' '}; //array to print spaces
//print line
if(n == lineNames[count])
{
lineAr[2] = n;
}
else
lineAr[2] = '-';
for(int x = 0; x<5; x++)
{
System.out.print(lineAr[x]); //prints to monitor
outputfile.print(lineAr[x]); //prints to output file
}//end for loop
System.out.println();
//print space
if(n == spaceNames[count])
{
spaceAr[2] = n;
}
else
spaceAr[2] = ' ';
for(int x = 0; x<5; x++)
{
System.out.print(spaceAr[x]);
outputfile.print(lineAr[x]);
}//end for loop
System.out.println();
//print line C
if(n == 'C')
{
lineAr[2] = n;
}
else
lineAr[2] = '-';
for(int x = 0; x<5; x++)
{
System.out.print(lineAr[x]);
outputfile.print(lineAr[x]);
}//end for loop
System.out.println();
outputfile.close();
}//end printLine method
I tried manually making the file and had the code to print to that file however, the file is empty.
Upvotes: 2
Views: 374
Reputation: 160
i hope this works
FileWriter writer = new FileWriter("testfile.txt");
for(int i = 0; i < 10; i++){
System.out.println("a");
writer.append("a");
}
writer.close();
This will print to the console as well as write to the file - 'testfile.txt
Upvotes: 0
Reputation: 2686
Try using write()
instead of print
for(int x = 0; x<5; x++)
{
System.out.print(lineAr[x]); //prints to monitor
outputfile.write(lineAr[x]); //write to output file
}//end for loop
System.out.println();
Upvotes: 1