Reading each keystroke from a console app?

I'm using Sun JDK 1.3.0_02 on RedHat Linux 7.1.
I've written a console application (no GUI, no Swing), from which I need to read each keystroke from the keyboard as it is typed.
My loop basically waits (blocks) on System.in.read(), and disposes of each byte as it is read.
Unfortunately, the way the app executes, my Java app doesn't seem to be given any keyboard input until the user presses ENTER. In addition, each keystroke is echoed to the console display, which I don't want.
Can anyone point me in the right direction to solve this? I can't use any GUI components as this needs to be a console app.
Thank you,
Bryan

This can be fixed with a tiny JNI program. As long as the 'c' call getch() works the same on all platforms:
// The Java class
import java.io.*;
public class ConsoleInputStream extends InputStream
    public native int read();
    static
        System.loadLibrary("ConsoleInputStream");
// The JNI header
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class ConsoleInputStream */
#ifndef _Included_ConsoleInputStream
#define _Included_ConsoleInputStream
#ifdef __cplusplus
extern "C" {
#endif
#undef ConsoleInputStream_SKIP_BUFFER_SIZE
#define ConsoleInputStream_SKIP_BUFFER_SIZE 2048L
/* Inaccessible static: skipBuffer */
* Class:     ConsoleInputStream
* Method:    read
* Signature: ()I
JNIEXPORT jint JNICALL Java_ConsoleInputStream_read
  (JNIEnv *, jobject);
#ifdef __cplusplus
#endif
#endif
// The JNI 'C' code
#include "..\classes\generated source\consoleInputStream.h"
#include "conio.h"
JNIEXPORT jint JNICALL Java_ConsoleInputStream_read(JNIEnv * env, jobject obj)
    return getch();
// The test program
public class Console
    public static void main(String[] args)
        try
            System.setIn(new ConsoleInputStream());
            while(true)
                int ch=System.in.read();
                if(ch=='\r')
                    break;
                else
                    System.out.print((char)ch);
        catch(Exception ex)
            ex.printStackTrace();
// the build script (Windows)
cl -I\j2sdk1.4.0\include -I\j2sdk1.4.0\include\win32 ConsoleInputStream.cpp /MD /LD user32.lib /link/out:..\classes\ConsoleInputStream.dllHope this helps :)

Similar Messages

  • Reading Each String From a text File

    Hello everyone...,
    I've a doubt in File...cos am not aware of File.....Could anyone
    plz tell me how do i read each String from a text file and store those Strings in each File...For example if a file contains "Java Tchnology forums, File handling in Java"...
    The output should be like this... Each file should contains each String....i.e..., Java-File1,Technology-File2...and so on....Plz anyone help me

    The Java� Tutorials > Essential Classes: Basic I/O

  • Reading each value from spreadshee​t file with delay (multiple rows and columns)

    Hi,
    a) I want to read EACH VALUE from a spreadsheet file having multiple rows and columns WITH DELAY. I am attaching my VI and sample datalog file for reference (tempsensor.txt).I need to do so because as soon as I read put ON the Sensor button on front panel, LV reads all the values at one go. I need the values for each temperature to be displayed after a delay.
    b) Secondly, I would like to read another file containing the state of four antennas (deployed:1; undeployed:0). I am logging state of each antenna in each column of the file(magnet.txt) I need to have four LEDS on front panel to display state of the antennas. I dont know what I have done for antennas in my VI is right or wrong. I guess thats rhe wrong way to approach the problem. Please help!!!(column1: Antenna1 state ; Column2:Antenna2 state.. and so..on..)
    Any help would be greatly appreciated!!
    Thanks in advance,
    Ratnesh
    FYI: The first column in my datalog file represents timestamp(number of seconds elapsed), second column: reading for temperature sensor 1, third column: reading for temperature senosr 2, and so on. I am using approx. 11 temperature sensors.
    Also, I have generated the log files for the reference purpose only. They do not represent the actual values. They are far away from actual values.
    Attachments:
    01032005.zip ‏30 KB

    Look at this modified version of your VI. After looking at it, I determined that a shift reggister was not required in this case.
    Lynn
    Attachments:
    MultiSensors.2.vi ‏85 KB

  • Reading a String from the Console.

    Hello,
    I am new to Java... I have to write a program which will read a long value from the console. Can somebody help me in this? or can i read it as a string and then convert to Long ? I prefer the second one as I am planning to convert this code to read a SOAP message... Can somebody help me or pint me to the right direction?
    Thanks,

    Reading it as a string and then parsing it (Long.parseLong(...)) is the way to do this.
    As far as converting to SOAP - slow down. If you're just getting started with java, you're going to be biting off a lot trying to tackle SOAP

  • Need FMS Guru! to Read substitution.xml from Server Side Apps

    I know how to read XML file from HTTP using XML.load(url),
    but there are some config node i need to read from substitution.xml
    from conf folder. Seems like XML.load doesn't allow accessing
    Physical path from "D:\Program Files\Adobe\Flash Media Server
    3\conf" - I am new in FMS Development, I dont know how to access
    them from Server side. Help pls.

    Thanks by your help Shanu.
    Nevertheless, finally I tryed the easiest way (pass the parameter with 'GET'). Moreover I found why my code wasn't working. It was a fool thing. I though PDA connect throught a proxy, but it wasn't true. Whatever.
    Regards.
    FSG.
    The final script on the xml-report is:
    <report type="Validacion Online" required="false" multiple="false" attachments="false" scriptref="store://this/reportdef/script[@name='ValidacionOnlineValidation1']">
         <field sortid="0" id="Poliza" inputtype="textbox" label="Poliza" rows="1" wide="false" required="false"/>
    </report>
    <script name="ValidacionOnlineValidation1" script="if (0 == 0)
    var szURL="http://URL/vonline/vonline?parameter1=";+Poliza.value;                         
    var m_HttpReq = new ActiveXObject("Pocket.HTTP");                                             m_HttpReq.timeout = 15000;
    var m_HttpResponse = m_HttpReq.GetResponse(szURL,"");
    window.alert(m_HttpResponse.string);
    if (m_HttpResponse.statusCode==200)  {....}
    else {....}

  • Read each button from a gamepad

    Hi, what I would like to do is read input from a usb gamepad  and change a Color box and change text infront of the box. However, the controller outputs a t/f for each button.
    (Button 1,2,3,4 will change color, and 5,6,7,8 will determine what text will display over the color box( 4 diff text displays))
    My problem is how do I say "Def. If neither 1,2,3,4 are presses-black, If button 1 is pressed-blue, If button 2 is pressed-green...etc..."
    I have tried a case structure, but they can only say T/F once, which would be fine but the color box can only accept one input... I have attached a picture of what I have that wont work, I need an alternative...
    Thank you, 
    Brent S.
    Attachments:
    Visual.PNG ‏26 KB

    Since your data is already a cluster you can use the Cluster to Array, then use the seach 1D array for a True eliminating the need for the build array.
    Unofficial Forum Rules and Guidelines - Hooovahh - LabVIEW Overlord
    If 10 out of 10 experts in any field say something is bad, you should probably take their opinion seriously.

  • [Solved ]Problems with a programs started from a console app

    Ok, i'm using Midnight Commander like my file manager. It runs well, but i have a problem:
    When i run first  urxvt and then MC, i can open any file and close MC after this, and the file is still open in its respective app. But if i run MC directly from a menu or Run dialog with: urxvt -e mc and i open a file, when i close MC, the file is closed too.
    How can i avoid this? I really want to can close MC without close the files that i have opened. In my Fluxbox's menu i putted an entry for MC with that command, is it the correct command for this?
    Thank you!
    Last edited by superchango (2012-06-29 18:07:54)

    See if adding -hold to the urxvt command helps
    man urxvt wrote: -hold|+hold
               Turn on/off hold window after exit support. If enabled, urxvt will not immediately destroy its window when the program
               executed within it exits. Instead, it will wait till it is being killed or closed by the user; resource hold.

  • Calling Adobe Reader for iOS from my iOS App

    I have an iOS application that allows readers to view PDF Documents in a child window; Some users want the full search and navigation features of Adobe Reader for iOS, so I would like to be able to pass the PDF Link to the Adobe Reader App on the users iPad .  I am assuming Adobe Reader supports HandleOpenURL so I should be able to launch Adobe Reader and pass it the document using some syntax like:
    AdobeReader://myDocLink.pdf
    However I dont know the proper syntax, or if Adobe supports it. Anyone know? thanks!

    Satyadev, thanks. Is the ability to "Open with Adobe" Available to developers as an API or library?  Basically I'm using a UIWebView to show the linked Adobe document (ie, "http://mywebserver/documents/myManual.pdf", but I don't want to code in all of the search and navigation features for PDFs;  I want the user to be able to click a button and launch the Adobe Reader App Like safari provides.    ANy suggestions?

  • Converting Console App to Windows Service

    I'm trying to convert a Console Application to a Windows Service, so I move the code from the Main procedure (in the Console App) to the OnStart event (in the Service).  I set the account property to LocalSystem, put in the correct command line parameters and change the Startup object to the Service (instead of the main).  I compile, install and start the service.  I write to the event log to confirm the service is working properly.  When I click the Test Connection button in SM59 I get the error that the program isn't registered.  When I do this from the Console App everything work fine.
    Any thoughts?
    Thanks,

    Another important point it the command line: You should know that services have two command lines: One written in the registry and passed to the Main function (that is usually hidden in the framework). The other is the one passed to OnStart(). This one is really unusual: You have to type these parameters in the manual start dialog of the Services MMC. So you better don't use is and take your paramters from somewhere else.

  • Console app from labview VI

    Hi,
    I have a VI which I have turned into an EXE and it works fine (as a dialog-based app). I now want to use this EXE as a console app -- be able to give the input AND receive the resulting output on the command prompt. How can I do this?
    I know how to pass in arguments to my EXE from command line. The problem is how do I output the result (bunch of strings) back to the command prompt?
    One solution I guess is to build a DLL from my VI and then create a console app in VC++ calling this dll in it.
    Any other ideas? examples?
    TiA!
    Khalid

    Hi,
    For the output...
    Use GetStdHandle, kernel32 to get a handle, (handle GetStdHandle(long
    param), use -11 for parameter);
    Use WriteFile, kernel32 to write a string (long WriteFile(long handle, CStr
    message, long length, long *written, long overlapped));
    It actually works!
    Regards,
    Wiebe.
    "Wiebe@AIR" wrote in message
    news:3e6ef96f$0$157$[email protected]..
    > Hi,
    >
    > If it is a windows app, you can read the command line, just line you would
    > in another language. This is tricky, because the GetCommandLine api works
    > with an array of strings, where each element is \00 delimited, and the
    last
    > element is \00 \00 deleimited.
    >
    > For the output, I have no idea...
    >
    > If you want a VI to read the command line, let me kn
    ow your email address.
    > But be aware that the command line returns "LabVIEW.exe" when it's called
    > from the development environment. If you have started LabVIEW by dubble
    > clicking a VI in the windows explorer, it says "LabVIEW.exe "c:\vi
    > path\vi.vi"" (or something like this).
    >
    > Regards,
    >
    > Wiebe.
    >
    >
    > "Khalid" wrote in message
    > news:[email protected]..
    > >
    > > Hi,
    > >
    > > I have a VI which I have turned into an EXE and it works fine (as a
    > > dialog-based app). I now want to use this EXE as a console app -- be
    > > able to give the input AND receive the resulting output on the
    > > command prompt. How can I do this?
    > >
    > > I know how to pass in arguments to my EXE from command line. The
    > > problem is how do I output the result (bunch of strings) back to the
    > > command prompt?
    > >
    > > One solution I guess is to build a DLL from my VI and then create a
    > > console app in VC++ calling this dll in it.
    > >
    > > A
    ny other ideas? examples?
    > >
    > > TiA!
    > >
    > > Khalid
    > >
    >
    >

  • HT2534 I have downloaded free apps from the apple App Store but each time they charge me 8 dollars for a free app. A free app shoud be free to download . How do I get my money back?

    I have downloaded free apps from the apple App Store but each time they charge me 8 dollars for a free app. A free app shoud be free to download . How do I get my money back?

    iOS is the operating system for iOS devices like the iPhone and iPad. Your Mac runs on OS X. You have installed OS X 10.10.2 Yosemite.
    I have the most recent version of the Kindle app for Mac from the Mac App Store (MAS) v. 1.10.6 and it works fine. Look again in the MAS for the Kindle app, does it say Get or Open on the button?
    Are you confusing Kindle for Mac with Kindle for iOS. The iOS version won't run on your Mac.

  • App.alert show over and over after each keystroke

    I am preparing a pdf form for my department in which doctors will need to quantify the amount of tracer found in 17 heart arteries. The amount of tracer in the patient will be compared when the patient is under stress and when he is at rest.
    Then it will calculate the sum of the 17 scores at stress (SSS) and the sum of the score at rest (SRS), and then will calculate the difference between the 2 scores (SDS).
    The rationale is that the score of each 17 segments at rest cannot (should not) be higher than the score at stress, however under a few circumstances this can happen. But to be sure that the user knows it's abnormal, it will tell that it should not be like that, and need to agree this is the case.
    The problem is that if this happen, each keystroke thereafter will re-trigger the question. How can I make sure that once it asks the question for that particular segment, it will not ask it again?
    The other issue is that in these rare cases, we still want to collect what should be the answer if this didn't happen. So I created another set of score at rest (these will be hidden on the final form, but left it there so I can see the results during the design of the form) that should copy the results of the raw data. But in the case of when the rest score is higher than the stress score, it will take the stress value. The problem is that it calculates the SRS one stroke late. How do I fix this?
    Here is a link to my form.
    Dropbox - Sample Perfusion form.pdf

    // The Fieldname shoud have the following hierarchy-Name-Format
    // It's important in my case that the naming of the fields for stress and rest perfussion have the follwing format: "Part1.Part2.99 " (Parent-Child-Format)
    // sample:
    // "Feld.sss.10", "Feld.sss.11"........"Feld.sss.27"
    // "Feld.srs.10", "Feld.srs.11"........"Feld.srs.27"
    // for this code its important that the last to char have two digits: 01 intead of 1, 02 instead of 2 etc..
    // Better you begin with 10 and 11,12,13..27
    // The other three result fields a named xsss, xsrs, xsds.
    // The two raw field, i didn't make. You must describe in more detail.
    // This is the main core. The rest is very little and easy.
    xFeldname = "Feld."        // Fieldname Part1 for Stress/Rest Perfusion (Parent or Groupname)
    xFeldExtSss = "sss."        // Fieldname Part2 for Stress Perfusion (Child 1)
    xFeldExtSrs = "srs."         // Fieldname Part2 for Rest Perfusion (Child 2)
    xFieldSSS = "xsss"          // Fieldname for calculated Field SSS (as I understand it: sum of the Stress Perfusion, less than 9)
    xFieldSRS = "xsrs"          // Fieldname for calculated Field SRS (as I understand it: sum of the Rest Perfusion, less than 9)
    xFieldSDS = "xsds"         // Fieldname for Field SDS (as I understand it: It's the difference from the Field SSS and SRS)
    sxsField = this.getField(xFeldname)
    sxsField.setAction("Validate", "xcompare(event.targetName, event.value)")
    if (typeof okFields == "undefined") {
        okFields = new Array()
    function xcompare(xField, xValue) {
        var xSuff = xField.substring(xField.length - 2)
        var srsName = xFeldname + xFeldExtSrs + xSuff
        var sssName = xFeldname + xFeldExtSss + xSuff
        if (xField == srsName) {
            var xSSS = this.getField(sssName).value
            var xSRS = xValue
            var srsorsss = xFeldExtSrs
        } else {
            var xSSS = xValue
            var xSRS = this.getField(srsName).value
            var srsorsss = xFeldExtSss       
        if (xSRS > xSSS) {
            if (okFields.indexOf(xSuff) == -1) {
                if (app.alert("..your alert: The SRS is bigger than SSS. Is this OK?......", 2, 2) == 4) {
                    okFields.push(xSuff)
                    this.getField(srsName).textColor = color.red
                    this.getField(sssName).textColor = color.red
                } else {
                    event.rc = false
                    return
        } else {
            var xFind = okFields.indexOf(xSuff)
            if (xFind != -1) {
                delete okFields[xFind]
                this.getField(srsName).textColor = color.black
                this.getField(sssName).textColor = color.black
        if (event.rc = true) xcalculate(xField, xValue, xSuff, srsorsss)
    function xcalculate(xField, xValue, xSuff, srsorsss) {
        var xTemp = xField.substring(0, xField.length - 2)
        var xSum = 0
        if (xValue >= 1 && xValue < 9) {
            var sxsField = this.getField(xTemp)
            var xTemp = sxsField.getArray()       
            xSum = parseInt(event.value)
            for (i = 0; i < xTemp.length; i++) {
                if (xValue < 1 || xValue > 8) continue
                if (xTemp[i].name == xField) continue
                if (xTemp[i].value == "") continue
                if (xTemp[i].value > 8) continue
                xSum += parseInt(xTemp[i].value)       
            if (srsorsss == xFeldExtSss) {
                this.getField(xFieldSSS).value = xSum
            } else {
                this.getField(xFieldSRS).value = xSum
            this.getField(xFieldSDS).value = this.getField(xFieldSSS).value - this.getField(xFieldSRS).value

  • Calling Console App from Win Interface

    Need to call a console app[long running process] from a windows interface, such that
    1. The interface remains active after calling the console app
    2. So that I am able to fire another call via interface to the console app
    3. And these two would run concurrently 
    Some googling around gave me certain solutions... will try today .
    1. From Win Forms Interface , I call my console app with this code
    [Link]
    ProcessStartInfo oStartInfo = new ProcessStartInfo()
    oStartInfo.FileName = ApplicationName;
    oStartInfo.Arguments = BaseOptions + MyLoopLoadedItemsHere;
    Process.Start(oStartInfo)
    2. Use the background worker class in the interface component and then call the console app.
    3. Or Any thing else ?
    However feedback required on whats the best approach according to you

    You are on the right track. However you don't need to use a background worker class in this particular case. The line "Process.Start(oStartInfo)" returns immediately  and the process will run in parallel to yours.

  • I recently loaded OSX mavericks on my Imac. I now find I cannot open any Adobe products from CS5. The error message reads " to open Adobe illustrator CS5.app, you need to install a JAva SE 6 runtime. Would you like to check and install one?

    I recently loaded OSX mavericks on my Imac. I now find I cannot open any Adobe products from CS5. The error message reads " to open Adobe illustrator CS5.app, you need to install a JAva SE 6 runtime. Would you like to check and install one? I try to install but get the error" download error". As far as i know I'm using Adobe Java 7. None of my CS5 suite works anymore............and i really dont want to upgrade to a monthly cloud service fee as i hate this policy with a passion.

    This goes for Dreamweaver CC on Mavericks!!!!! THANK YOU!
    I couldn't launch Dreamweaver CC. An error told me to install "java se 6 runtime". But when I clicked  OK I got another error telling me there is a network problem! I found this forum post on CS6 products, so I tried the download link, installed java 6 and presto, it worked! Thanks!

  • How to read and write data from json file from windows phone7 app

    Hi
    I am developing wp7 app for the use of students my questions are
    How can i write a code to read and write the json/text file for the wp7.
    I am using windows 7 OS, VS 2010 Edition.
    This is my code below:
    xaml:
    <Grid>
                        <TextBlock Height="45" HorizontalAlignment="Left" Margin="7,18,0,550" Name="textBlock1" Text="Full
    Name: " />
                        <TextBox Width="350" Height="70" HorizontalAlignment="Left" Margin="108,1,0,0" Name="txtName"
    Text="Enter your full name" VerticalAlignment="Top" />
                        <TextBlock Height="45" HorizontalAlignment="Left" Margin="6,75,0,0" Name="textBlock2" Text="Contact
    No: " VerticalAlignment="Top" />
                        <TextBox Width="350" Height="70" HorizontalAlignment="Left" Margin="108,61,0,480" Name="txtContact"
    Text="Enter your contact number" MaxLength="10" />
                        <Button Content="Register" Height="72" HorizontalAlignment="Left" Margin="10,330,0,0" Name="btnRegister"
    VerticalAlignment="Top" Width="190" Click="btnRegister_Click" />
                    </Grid>
    xaml.cs:
    private void btnRegister_Click(object sender, RoutedEventArgs e)
                string name, contact;
                name = txtName.Text;
                contact = txtContact.Text;
                try
                    if (name != "" && contact != "")
                        string msg = name + " " + contact;
                        MessageBox.Show(msg);
                        Student stud = new Student
                            Name= name,
                            Contact = contact,
                        string jsonString = JsonConvert.SerializeObject(stud);
                        MessageBox.Show(jsonString);
                    else
                        MessageBox.Show("Input Proper Information", MessageBoxButton.OK);
                catch (Exception ex)
                    MessageBox.Show(ex.Message);
    I have download NewtonSoft.json version 5.0.8.
    So, I am able to convert input data into json format, but how can I able to write and read this data from a json/text file.
    How can I do?
    Thank you in adv and please, reply soon.

    We don't have many samples left for Windows Phone 7 + Azure, the closest one to what you want to do is probably:
    Using Local Storage with OData on Windows Phone To Reduce Network Bandwidth
    this sample uses the local database feature: 'LINQ to SQL', available to Windows Phone 7.1 and 8.0 Silverlight applications, instead of simple file storage but even if you choose to stick with simple file storage I believe you should be able to adapt the
    networking related portions of the sample to your particular application.
    Eric Fleck, Windows Store and Windows Phone Developer Support. If you would like to provide feedback or suggestions for future improvements to the Windows Phone SDK please go to http://wpdev.uservoice.com/ where you can post your suggestions and/or cast
    your votes for existing suggestions.

Maybe you are looking for

  • Twitter for BlackBerry 10 updated to v10.2.1.2

    If you're a big user of Twitter for BlackBerry 10, then you'll be pleased to know that it has been updated. It's not my go to Twitter client but the updates lately have been pretty good and it is slowly becoming as good as it was on BlackBerry OS, at

  • Open PDF with Parameters has no effect if PDF is already open

    Hello Users, I try to open a PDF at a named destination. This works fine. But if the PDF is already open and I change the nameddest-Parameter, nothing happens. The Document don't jump to the new destination: I try this on the DOS-Shell, finally I wou

  • Dreamweaver CS5 to CS6

    I use to have Dreamweaver cs5 and I had created 2 websites from the program.  I now have Dreamweaver cs6 but I do not know how to import my recent webpages into cs6.  My webpage folders are on my desktop but when I click import site the open button i

  • RAM is not showing up, is slot broken?

    I have a macbook pro mid 2009 running Lion (upgraded twice). Right now, there are two sticks of 4gb RAM in the computer, however, if I go to about this mac, system profiler, or activity moniter, they all show that I have only 4gb, while I should have

  • Which process/application is requesting 'elevated privileges'?

    Every hour or so, I get a pop-up screen that asks for an administrator password and tells me: "Elevated privileges are required in order to complete installation. Type an administrator's name and password to allow this.", see screenshot below. The po