为什么我在Java中尝试阻止后无法打印到控制台?

roc*_*ger 1 java android try-catch

我在Android应用程序中有以下代码:

public static HttpResponse dbPost(String handlerUrl, List<NameValuePair> postData) {

    HttpClient httpclient = new DefaultHttpClient();
    String postUrl = constants.postUrl(); 
    HttpPost httppost = new HttpPost(postUrl);
    HttpResponse response = null;
    System.out.print("Catch 0");

    try {
        httppost.setEntity(new UrlEncodedFormEntity(postData));
        response = httpclient.execute(httppost);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.print("Catch 1");

    return response;

}
Run Code Online (Sandbox Code Playgroud)

我有一个调用此块的按钮.如果我按下按钮,控制台将打印"Catch 0"(但不是"Catch 1").如果我再次按下按钮(相同的实例),控制台将打印"Catch1Catch0".有什么问题?

我对Java有点新鲜,所以请耐心等待.

Ree*_*sey 8

因为你正在使用,你需要调用flushprint.

System.out.print("Catch 1");
System.out.flush();
Run Code Online (Sandbox Code Playgroud)

默认行为PrintStream是仅在写入换行符时刷新.(写入(int)中记录了此行为.)

如果您使用printLn而不是print,流将自动刷新.没有它,您需要显式刷新输出流.