IT Share you

System.out.println ()에 의해 콘솔에 인쇄 된 내용을 삭제하는 방법은 무엇입니까?

shareyou 2020. 11. 23. 20:29
반응형

System.out.println ()에 의해 콘솔에 인쇄 된 내용을 삭제하는 방법은 무엇입니까?


Java 응용 프로그램에서 System.out.println(). 이제 프로그래밍 방식으로이 항목을 삭제하는 방법을 찾고 싶습니다.

Google에서 해결책을 찾지 못했는데 힌트가 있습니까?


이전에 인쇄 된 문자 \b만큼 백 스페이스 문자 인쇄 할 수 있습니다 .

System.out.print("hello");
Thread.sleep(1000); // Just to give the user a chance to see "hello".
System.out.print("\b\b\b\b\b");
System.out.print("world");

참고 : 이것은 Mars (4.5) 이전 릴리스의 Eclipse 콘솔에서 완벽하게 작동하지 않습니다. 그러나 이것은 명령 콘솔에서 완벽하게 작동합니다. Eclipse 콘솔에서 작동하도록 백 스페이스 \ b를 얻는 방법 도 참조하십시오 .


Java에서 화면 지우기는 지원되지 않지만이를 달성하기 위해 몇 가지 해킹을 시도 할 수 있습니다.

a) Windows의 경우 다음과 같이 OS-depends 명령을 사용합니다.

Runtime.getRuntime().exec("cls");

b) 새 줄을 여러 개 넣으십시오 (이렇게하면 화면이 명확하다는 착각이 생깁니다).

c) System.out을 끄려면 다음을 시도하십시오.

System.setOut(new PrintStream(new OutputStream() {
    @Override public void write(int b) throws IOException {}
}));

커서를 위로 사용하여 줄을 삭제하고 텍스트를 지우거나 단순히 새 텍스트로 이전 텍스트로 덮어 쓸 수 있습니다.

int count = 1; 
System.out.print(String.format("\033[%dA",count)); // Move up
System.out.print("\033[2K"); // Erase line content

또는 명확한 화면

System.out.print(String.format("\033[2J"));

이것은 표준이지만 wikipedia에 따르면 Windows 콘솔은이를 따르지 않습니다.

보세요 : http://www.termsys.demon.co.uk/vtansi.htm


Java 프로그래밍에 blueJ를 사용하고 있습니다. 터미널 창의 화면을 지우는 방법이 있습니다. 이 시도:-

System.out.print ('\f');

이 줄 앞에 인쇄 된 모든 내용이 지워집니다. 그러나 이것은 명령 프롬프트에서 작동하지 않습니다.


System.out이며 PrintStream그 자체로는 출력을 수정하는 방법을 제공하지 않습니다. 해당 개체를 백업하는 항목에 따라 개체를 수정하거나 수정하지 못할 수 있습니다. 예를 들어, System.out로그 파일 로 리디렉션 하는 경우 이후에 해당 파일을 수정할 수 있습니다. 콘솔로 곧장 이동하는 경우 텍스트가 콘솔의 버퍼 상단에 도달하면 텍스트가 사라지지만 프로그래밍 방식으로 엉망이 될 방법은 없습니다.

정확히 무엇을 달성하고자하는지 잘 모르겠지만 PrintStream메시지가 출력되는대로 메시지를 필터링 하는 프록시 만드는 것이 좋습니다.


출력 화면을 지우려면 CTRL+ L(출력 지우기)를 눌러 실제 사람을 시뮬레이션 할 수 있습니다 . Robot () 클래스를 사용하여이 작업을 수행 할 수 있습니다.이를 수행하는 방법은 다음과 같습니다.

try {
        Robot robbie = new Robot();
        robbie.keyPress(17); // Holds CTRL key.
        robbie.keyPress(76); // Holds L key.
        robbie.keyRelease(17); // Releases CTRL key.
        robbie.keyRelease(76); // Releases L key.
    } catch (AWTException ex) {
        Logger.getLogger(LoginPage.class.getName()).log(Level.SEVERE, null, ex);
}

BlueJ에서 터미널을 지우는 방법에는 두 가지가 있습니다. BlueJ가 모든 대화 형 메서드 호출 전에 터미널을 자동으로 지우도록 할 수 있습니다. 이렇게하려면 단말기의 '옵션'메뉴에서 '메소드 호출시 화면 지우기'옵션을 활성화합니다. 프로그램 내에서 프로그래밍 방식으로 터미널을 지울 수도 있습니다. 용지 공급 문자 (유니 코드 000C)를 인쇄하면 BlueJ 터미널이 지워집니다. 예를 들면 다음과 같습니다.

System.out.print('\u000C');

BalusC의 답변에 추가하기 위해 ...

System.out.print("\b \b")지연과 함께 반복적으로 호출하면 {Windows 7 명령 콘솔 / Java 1.6}에서 백 스페이스를 누를 때와 똑같은 동작이 나타납니다.


Eclipse Mars에서 대체 할 줄이 적어도 지우고있는 줄만큼 길다고 안전하게 가정 할 수 있다면 단순히 '\ r'(캐리지 리턴)을 인쇄하면 커서가 보이는 모든 문자를 덮어 쓰려면 줄의 처음으로 다시 이동하십시오. 새 줄이 더 짧으면 공백으로 다른 줄을 만들 수 있다고 생각합니다.

이 방법은 내 프로그램 중 하나에서 뜯어 낸이 코드 스 니펫에서와 같이 실시간 업데이트 진행률을위한 일식에서 매우 편리합니다. 웹 사이트에서 미디어 파일을 다운로드하는 프로그램의 일부입니다.

    URL url=new URL(link);
    HttpURLConnection connection=(HttpURLConnection)url.openConnection();
    connection.connect();
    if(connection.getResponseCode()!=HttpURLConnection.HTTP_OK)
    {
        throw new RuntimeException("Response "+connection.getResponseCode()+": "+connection.getResponseMessage()+" on url "+link);
    }
    long fileLength=connection.getContentLengthLong();
    File newFile=new File(ROOT_DIR,link.substring(link.lastIndexOf('/')));
    try(InputStream input=connection.getInputStream();
        OutputStream output=new FileOutputStream(newFile);)
    {
        byte[] buffer=new byte[4096];
        int count=input.read(buffer);
        long totalRead=count;
        System.out.println("Writing "+url+" to "+newFile+" ("+fileLength+" bytes)");
        System.out.printf("%.2f%%",((double)totalRead/(double)fileLength)*100.0);
        while(count!=-1)
        {
            output.write(buffer,0,count);
            count=input.read(buffer);
            totalRead+=count;
            System.out.printf("\r%.2f%%",((double)totalRead/(double)fileLength)*100.0);
        }
        System.out.println("\nFinished index "+INDEX);
    }

이를 수행하는 가장 쉬운 방법은 다음과 같습니다.

System.out.println("\f");

System.out.println("\u000c");

다음을 성공적으로 사용했습니다.

@Before
public void dontPrintExceptions() {
    // get rid of the stack trace prints for expected exceptions
    System.setErr(new PrintStream(new NullStream()));
}

NullStream의 삶 import com.sun.tools.internal.xjc.util패키지는 그래서 모든 Java 구현으로 사용할 수 없을 수도 있지만 그것은 단지의 OutputStream자신을 작성하는 간단한 충분합니다.


I found a solution for the wiping the console in an Eclipse IDE. It uses the Robot class. Please see code below and caption for explanation:

   import java.awt.AWTException;
   import java.awt.Robot;
   import java.awt.event.KeyEvent;

   public void wipeConsole() throws AWTException{
        Robot robbie = new Robot();
        //shows the Console View
        robbie.keyPress(KeyEvent.VK_ALT);
        robbie.keyPress(KeyEvent.VK_SHIFT);
        robbie.keyPress(KeyEvent.VK_Q);
        robbie.keyRelease(KeyEvent.VK_ALT);
        robbie.keyPress(KeyEvent.VK_SHIFT);
        robbie.keyPress(KeyEvent.VK_Q);
        robbie.keyPress(KeyEvent.VK_C);
        robbie.keyRelease(KeyEvent.VK_C);

        //clears the console
        robbie.keyPress(KeyEvent.VK_SHIFT);
        robbie.keyPress(KeyEvent.VK_F10);
        robbie.keyRelease(KeyEvent.VK_SHIFT);
        robbie.keyRelease(KeyEvent.VK_F10);
        robbie.keyPress(KeyEvent.VK_R);
        robbie.keyRelease(KeyEvent.VK_R);
    }

Assuming you haven't changed the default hot key settings in Eclipse and import those java classes, this should work.


BalusC answer didn't work for me (bash console on Ubuntu). Some stuff remained at the end of the line. So I rolled over again with spaces. Thread.sleep() is used in the below snippet so you can see what's happening.

String foo = "the quick brown fox jumped over the fence";
System.out.printf(foo);
try {Thread.sleep(1000);} catch (InterruptedException e) {}
System.out.printf("%s", mul("\b", foo.length()));
try {Thread.sleep(1000);} catch (InterruptedException e) {}
System.out.printf("%s", mul(" ", foo.length()));
try {Thread.sleep(1000);} catch (InterruptedException e) {}
System.out.printf("%s", mul("\b", foo.length()));

where mul is a simple method defined as:

private static String mul(String s, int n) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < n ; i++)
        builder.append(s);
    return builder.toString();
}

(Guava's Strings class also provides a similar repeat method)


For intellij console the 0x08 character worked for me!

System.out.print((char) 8);

참고URL : https://stackoverflow.com/questions/7522022/how-to-delete-stuff-printed-to-console-by-system-out-println

반응형