EditableBufferedReader.java 1.39 KB
package pad.prac1;
import java.io.*;


public class EditableBufferedReader extends BufferedReader 
{
	private String line = "";
	private boolean returnKey = false;
	
	public EditableBufferedReader(Reader in)
	{
		super(in);
	}
	
	public EditableBufferedReader(Reader in, int sz)
	{
		super(in,sz);
	}
	
	private void setRaw() throws IOException, InterruptedException
	{
		String[] cmd = {"/bin/sh", "-c", "stty raw -echo </dev/tty"};
		Runtime.getRuntime().exec(cmd).waitFor();
	}
	
	private void unsetRaw() throws IOException, InterruptedException
	{
		String[] cmd = {"/bin/sh", "-c", "stty -raw echo </dev/tty"};
		Runtime.getRuntime().exec(cmd).waitFor();
	}
	
	public int read() throws IOException
	{
		return super.read();
	}
	
	public String readLine()
	{
		try 
		{
			setRaw();
		} 
		catch (Exception e) 
		{
			System.out.println("Couldn't set terminal in raw mode");
			return "";
		}
		while(!returnKey)
		{
			try 
			{
				int character = read();
				switch(character)
				{
					case 0x0D:
						returnKey = true;
						break;
					default:
						line += (char)character;
						System.out.print((char)character);
						break;
				}
			} 
			catch (IOException e)
			{
				System.out.println("Couldn't unset raw mode");
				break;
			}
		}
		try 
		{
			unsetRaw();
		} 
		catch (Exception e) 
		{
			System.out.println("Couldn't unset raw mode");
			return "";
		}
		System.out.println("");
		return line;
	}
}