平时见System.out.flush()的次数不多,所以比较生疏,今天在一程序中见到时,想不明白它是干什么用的,这不,一下搜到了stackoverflow,自感上面网友解释地的挺好的,故在此做一下整理,希望以后能在自己的开发中使用这一知识点。
问题应该由下面的程序引出,下面程序中主函数的while循环里有这样一条语句System.out.flush(),把它注释掉与否对执行结果没有一点影响,有人(包括我)对这一现象不理解,关于它的作用stackoverflow上SegFault首先引用了《 Sun Certified Programmer for Java 6 Exam by Sierra & Bates》中的一段话“When you write data out to a stream, some amount of buffering will occur, and you never know for sure exactly when the last of the data will actually be sent. You might perform many operations on a stream before closing it, and invoking the flush() method guarantees that the last of the data you thought you had already written actually gets out to the file”,并做出了如下解释:下面程序中之所以有无System.out.flush()执行结果一样,因为System.out是自动的刷新的,每当缓存里写入一个字节,就会自动刷新。原文请移步此处。
验证代码如下:
<span style="font-size:14px;">import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class ReverseApp
{
public static void main(String[] args) throws IOException
{
String input = null;
while(true)
{
System.out.print("Enter a string: ");
System.out.flush();
input = getString(); // read a string from keyboard
if( input.equals("") ) // quit if [Enter]
break;
// make a Reverser
Reverser theReverser = new Reverser(input);
StringBuffer output = new StringBuffer();
output = theReverser.doRev(); // use it
System.out.println("Reversed: " + output); //output the reversed string!
}
}
public static String getString() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
return input;
}
}
class Reverser
{
private String tempString = null;
public Reverser(String input)
{
this.tempString = input;
}
public StringBuffer doRev()
{
String[] strArray = tempString.split(" ");
StringBuffer stringBuffer = new StringBuffer();
for(int i=(strArray.length-1); i>=0; i--)
{
stringBuffer.append(strArray[i]); //the tyle of str2 here is StrinfBuffer, it is efficient the String!
stringBuffer.append(" ");
}
return stringBuffer;
}</span>
}
以上代码恰能实现字符串中的反转,不过只能以单词为基本单元的字符串的反转,若字符串中只有一个单词,则原样输出;当然要实现单词(有时候未必是有一个意义的单词,反正就是字符串里没有空格,给人以单词的感觉)的反转输出也是有办法的,将在下篇博文里讨论。
上述代码的运行结果如下(不输入字符串,直接进Enter,程序会退出):