java - 如何同时打印到文件和显示器?

标签 java file console filewriter printwriter

我试图在打印到显示器的同时打印到文件。顺便说一句,它可以完美地打印到显示器上。我的代码甚至没有创建文件。这非常令人困惑,因为我在代码的其他部分创建了一个文件并且它运行良好。

我知道有一个 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/

相关文章:

java - 如何在 Java 中围绕一个点旋转多边形/点

具有两个不同版本 Jersey 服务器的 Java 客户端

linux - 命令了解文件夹中安装的内容

javascript - 在控制台面板中编辑 HTML 时没有 setAttribute 或 getAttribute

javascript - Chrome - javascript 控制台不工作

java - itext 在 PDF 中嵌入字体

java - 下载程序后无法通过进程运行程序(Java)

c - 文本被 append 在文件的开头而不是文件的末尾

java - 如何使用文件列表中的一个文件

linux - 在 Linux 上重命名多个文件同时保持相同的扩展名