【问题标题】:How to print to a file and the monitor at the same time?如何同时打印到文件和显示器?
【发布时间】:2017-12-11 04:10:16
【问题描述】:

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

我知道有一个 solution 来解决与我类似的问题,但是我还没有了解 FileOutputStream 或 PrintStream。我正在上编码课,我们只能使用课堂上教过的东西。有没有其他方法可以做到这一点?

下面是我的代码。

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

我尝试手动制作文件并有代码打印到该文件但是,该文件是空的。

【问题讨论】:

  • 谢谢,但我还没有了解 FileOutputStream,我只能使用我们在课堂上学到的东西。还有另一种方法可以做到这一点吗? @vinS

标签: java file console filewriter printwriter


【解决方案1】:

尝试使用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();

【讨论】:

  • 您好,谢谢您的回答。不幸的是 write 也不起作用。
【解决方案2】:

我希望这有效

    FileWriter writer = new FileWriter("testfile.txt");
    for(int i = 0; i < 10; i++){
        System.out.println("a");
        writer.append("a");
    }

    writer.close();

这将打印到控制台并写入文件 - 'testfile.txt

【讨论】:

    猜你喜欢
    • 2012-01-27
    • 2012-03-08
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多