我试图在打印到显示器的同时打印到文件。顺便说一句,它可以完美地打印到显示器上。我的代码甚至没有创建文件。这非常令人困惑,因为我在代码的其他部分创建了一个文件并且它运行良好。
我知道有一个 solution然而,对于与我类似的问题,我还没有了解 FileOutputStream 或 PrintStream。我正在学习编码类(class),我们只能使用类里面教授的内容。还有其他方法可以实现吗?
下面是我的代码。
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
我尝试手动创建文件并让代码打印到该文件,但是该文件是空的。
最佳答案
尝试使用 write()
而不是 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();
关于java - 如何同时打印到文件和显示器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47746314/