2016-09-10 29 views
4

我对Java很新颖。Java'System.err.format''''n'后跟'System.out.println',println打印在中间

我使用的是Ubuntu 16.04,JDK 8u101,Netbeans8.1。

当试图验证码:

public static void main(String[] args) { 
    System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line "); 
    System.out.println("Shouldn't this be the third line,prints at 2nd line"); 
} 

输出是:

This Prints At 1st Line 
Shouldn't this be the third line, but prints at 2nd line 
This Prints At 3rd Line, Shouldn't this be In 2nd Line 

为什么 “System.out.println” 打印在中间? 不应该最后打印。

我 “%n” 试图在最后& System.err.flush()这样的:

System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line%n"); 
System.err.flush(); 
System.out.println("Shouldn't this be the third line,prints at 2nd line"); 

还是相同的输出。

+2

您正在打印到两个不同的流,它们只在行的末尾刷新,但System.err在第二行末尾没有刷新。 –

回答

5

你是不是调用println()电话和System.outSystem.err之间flush()都(独立)缓冲PrintStream(S)。

// and you need a %n on the end to make 3 lines. 
System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line%n"); 
System.err.flush(); // <-- only needed if the previous write doesn't have 
        //  an implicit flush(); newline (%n) does. 
System.out.println("Shouldn't this be the third line,prints at 2nd line"); 
+0

System.err没有被刷新,因为它最后没有换行符。因此您需要手动冲洗。 +1如果你添加%n,我认为你不需要flush() –

+1

@PeterLawrey更正。 Javadoc说*可以创建一个'PrintStream'来自动刷新;这意味着在写入字节数组后,会自动调用'flush'方法,调用'println'方法之一或者写入换行符或字节(''\ n'')* –

+0

我试过码。我复制粘贴,保存,然后再次运行。我得到了相同的输出。 – Jit

相关问题