일반 BufferedReader.readLine() hangs

황제낙엽 2012.02.23 14:03 조회 수 : 2601

증상은 BufferedReader 의 readLine() 함수만 호출하면 멈춰버리는 현상

원인은 readLine() 함수가 carridge return이나 line feed가 나올때까지 대기하기 때문이라고 하는데 해결은 아래와 같이 BufferedReader.ready() 함수를 이용하여 준비상태를 확인해주는 것이다


I debugged a simple program to learn JavaCompiler in new JDK, but found BufferedReader.readLine() hangs for some reason. BufferedReader.readLine() returns null toindicate that you have reached the end of the data stream (i.e. the remote has closed). At all other times, readLine() will block until there is a complete
line (i.e. a message terminated by a newline). If you need to know that there is data before attempting to read, try to use BufferedReader.isReady() method.

Here is the sample code:
        Runtime run = Runtime.getRuntime();
        Process p = run.exec("java");

        BufferedInputStream in = new BufferedInputStream(p.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
       
        if (br.ready()) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } 


다른 방법에 대해서도 나와있긴한데 별로 좋은 방법처럼 보이지는 않지만 혹시나해서 스크랩해둔다

스레드를 이용해서 waitFor() 를 강제 수행하고 있다


package dfi.exloadv3;

 

import java.util.*;

import java.io.*;

 

public class ShellCmd  extends Thread {

 

    private Process pProcess = null;

    private String resource_info = "";

    private int    return_code = -1;

    private boolean debug_mode = false;

    private String  cmd = null;

       private String cmdlog_file = null;

       private String cmderr_file = null;

   

    public void setCmd( String cmd )

    {

        this.cmd = cmd;

    }

    public void setCmdLogFile( String cmdlog_file )

    {

        this.cmdlog_file = cmdlog_file;

    }

    public void setCmdErrFile( String cmderr_file )

    {

        this.cmderr_file = cmderr_file;

    }

   

    public void run()

    {

        StringBuffer result = new StringBuffer();

        String line = "";

        BufferedReader stdout = null;

        BufferedReader stderr = null;

        BufferedWriter bwout = null;

        BufferedWriter bwerr = null;

        try

        {

               if( this.cmd != null && this.cmd.length() > 0 )

               {

                     if( cmdlog_file == null || cmdlog_file.length() <= 0  )

                     {

                            File tfile = new File( cmd );

                            if( tfile.exists() == true )

                            {

                                 cmdlog_file = cmd+ ".log";

                            }

                            else

                                   cmdlog_file = "/dev/null";

                     }

                     if( cmderr_file == null || cmderr_file.length() <= 0  )

                     {

                            File tfile = new File( cmd );

                            if( tfile.exists() == true )

                            {

                                   cmderr_file = cmd+ ".log";

                            }

                            else

                                   cmderr_file = "/dev/null";

                     }

                    

                   pProcess = Runtime.getRuntime().exec(  this.cmd   ); 

                stdout = new BufferedReader( new InputStreamReader(pProcess.getInputStream()) );

                  stderr = new BufferedReader(new InputStreamReader(pProcess.getErrorStream()));

               bwout = new BufferedWriter(new OutputStreamWriter( new FileOutputStream( this.cmdlog_file )));

               bwerr = new BufferedWriter(new OutputStreamWriter( new FileOutputStream( this.cmderr_file )));

                   while( (line = stdout.readLine()) != null )

                     {

//                       result.append( line + "n" ); 

                         bwout.write(line + "n" );

                     } 

                while( (line = stderr.readLine()) != null )

                     {

//                       result.append( line + "n" ); 

                      bwerr.write(line + "n" );

                     }  

                resource_info = result.toString();

               }

               else

               {

                     System.out.println("    [Error] Coammnd Emtpy");

               }

        }

        catch( Exception e)

        {

               System.out.println( e.toString() );

        }

        finally{

               try

               {

                      if( bwout != null )

                            bwout.close();

                      if( bwerr != null )

                            bwerr.close();

                      if( stdout != null )

                            stdout.close();

                      if( stderr != null )

                            stderr.close();

               }catch (IOException e)

               {

                    

               }

        }

    }

   

    public boolean WaitProcess()

    {

        boolean bRet = false;

        try

        {

            while( true )

            {

                if( this.isAlive() == false )

                {

//                      System.out.println( this.getName() + "    Status : "+ this.getState());

                   pProcess.waitFor();                    

//                        System.out.println( " result : " + resource_info ) ;

                   return_code = pProcess.exitValue();

                    System.out.println("  return code : " + return_code );

                    if( return_code == 0 )

                         bRet = true;

                   break;

                  }

            } 

        }

        catch( Exception e)

        {

                 System.out.println( e.toString() );

        }

        return bRet;

    }

 

    public static void main(String[] args) 

    {

          String cmd = null;

        

          ShellCmd jt = new ShellCmd();

          cmd = "ls";

          jt.setCmd( cmd );

          jt.start();

          jt.WaitProcess(); 

    }

}



번호 제목 글쓴이 날짜 조회 수
347 java.util.Optional 에서의 map() 함수의 이해 황제낙엽 2026.06.24 666
346 linux(ubuntu) 의 jdk 21 이 설정된 환경에서 jdk 17 로 다운그레이드 절차 황제낙엽 2025.09.22 1532
345 [ChatGPT] javax.* 패키지와 jakarta.* 패키지의 혼합 사용 방안 황제낙엽 2025.04.15 2458
344 [ChatGPT] *.servlet.http.HttpServlet 클래스를 사용할 수 있는 주요 WAS 목록 황제낙엽 2025.04.14 2038
343 [ChatGPT] JDBC API에서 java.sql과 javax.sql 패키지의 차이점 황제낙엽 2025.01.31 2218
342 jakarta.servlet 패키지를 이용한 File Upload 구현 (2024.03.03, Servlet 5.0) 황제낙엽 2025.01.02 2310
341 [ChatGPT] Java EE가 Jakarta EE로 전환 황제낙엽 2025.01.01 2525
340 [ChatGPT] File.delete() 함수로 파일 삭제가 되지 않는 경우 황제낙엽 2024.12.10 2809
339 [ChatGPT] <jsp:include>에서 flush="true"를 설정시의 몇 가지 문제점 과 대안 황제낙엽 2024.07.19 2493
338 [Copilot] JSP, Servlet, web.xml, mysql 한글 설정 황제낙엽 2024.07.12 2555
337 Base64 클래스의 encode, decode 에서 URL-safe 황제낙엽 2024.07.10 2624
336 [Copilot] JSP 에서 다른 페이지를 현재 페이지에 포함시키는 문법 (include) 황제낙엽 2024.06.26 2570
335 Exception 출력에 대한 고찰 황제낙엽 2024.06.10 2198
334 google-auth-library-oauth2-http 라이브러리 다운로드 황제낙엽 2023.11.19 4025
333 firebase-admin-java 라이브러리 다운로드 (firebase admin sdk library) 황제낙엽 2023.11.19 2805
332 Enum 활용 (개인블로그, Effective Java) file 황제낙엽 2023.11.02 2759
331 Enum 활용 (우아한기술블로그) file 황제낙엽 2023.11.02 2790
330 servlet name 에 camel case 를 사용해서는 안되는 이유 황제낙엽 2023.10.24 2508
329 org.apache.commons.fileupload.servlet.ServletFileUpload 이용 예시 황제낙엽 2023.08.25 3336
328 ServletFileUpload.parseRequest() 실행 결과 리스트가 비어있는 오류 황제낙엽 2023.08.25 2935