Command Line Input Terminating with Ctrl+D

Hi,
I am writing a program, that gets the input from the command line, what I want the program to do it continue to get the input until Ctrl+D is entered but I can not work out how to do this.
Has anyone got any ideas.
Thanks,
Adam

Are you working in a unix system? If so, Control-D means end-of-input, so you don't specifically look for a control-D character, you just check for end of input (end of the stream). This is provided in IO routines, in particular BufferedReader:
"Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached"
So for example:
import java.io.*;
public class test {
  public static void main(String argv[]) {
    String line;
    int i = 0;
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      while((line = in.readLine()) != null) {
        i++;
    } catch (IOException e) {
      e.printStackTrace();
    System.out.println("Now I'm done, having read " + i + " lines.");

Similar Messages

  • Calling C from Java. C takes in a command line input

    Hello,
    I have created some basic JNI programs, in which the java file calls the C files. The way I could do it was directly calling the functions in the C files, which I needed. Now I am trying to call a C file from Java, and the C files takes in a command line argument after being compiled.
    Also after compiling the C file, it produces an exe. I cannot change the C file and also want to call it from Java using JNI (as I want to later put all this into a jar and jnlp file and put it on webstart).
    If anyone can help me on how to call the compiled C file and how to send in the input as a command line argument I would greatly appreciate it.
    Thanks
    Nick

    Now I know how to create a C wrapper file and a Java file in JNI format. Does this mean you want to run the exe files by calling the main() method through JNI. Yes you can do that BUT you will need to turn your exe file into a dll and then write a JNI wrapper to act as a bridge between the Java and the dll.Yes. Thats exactly what I want to do. I want to call the C files through JNI. But what I am asking is, how do I send in the input which is originally sent in as stdin? And also what are the steps to follow if I want to call a main method of the C files in the JNI.
    Up till now I have been using JNI to call functions from the initial C files from the C wrapper file. But now I want to call the .exe file by sending it a command line input. Or if you can suggest a better method that would be great.
    You can execute an exe file using ProcessBuilder then there is no need for a JNI wrapper. You must read the 4 sections of [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html] and implement ALL the recommendations. Failure to do so will cause you much grief.
    You could achieve the same result but using a lot more code and a hell of a lot more effort by invoking the exe executables from JNI code that invokes the 'C' exec() library. Just thinking about that approach makes my eyes water!
    Well if I just use the exec() library I can do it, yes thats ture. But I wasnt sure if I did that, and then put this on Java Web Start, if non PC users can access it or not. If macs, and linux machines can access this even If i use exec, then my problem is solved.
    Thanks
    Nick

  • Command line input concurrency?

    I'm building an agent program with a number of classes that each require the user to input information at the command line (not with args, but using Scanner(System.in)). I've only just now realised that running two of these agents simultaneously will result in them both using the same input. Is there any way to allocate separate channels, or to allocate a flow of control so that one will not receive input that is destined for the other?
    Thanks to anybody who can help.

    I'm a bit confused about the Synchronise keyword. I've figured out that i'll need a separate shell/window/console/terminal/whatever for each agent. I'm not sure I can use System.in and System.out in this case.
    Currently each agent class uses a class called InputOutput. The code for it is pretty simple:
    import java.util.Scanner;
    class InputOutput {
        private Scanner reader;
        public InputOutput() {
            reader = new Scanner(System.in);
        public String input() {
            return reader.nextLine().trim().toLowerCase();
        public void output(String text) {
            System.out.print(text);
        public String prompt(String prompt) {
            output(prompt + "  ");
            return input();
        public boolean yesOrNo(String question) {
            while(true) {
                try {
                    output(question + " (Y/N)  ");
                    char correct = input().charAt(0);
                    switch(correct) {
                        case 'y': return true;
                        case 'n': return false;
                        default: throw new Exception();
                catch(Exception e) {
                    output("Invalid selection\n");
        public String convertToDollars(int cents) {
            StringBuffer price = new StringBuffer(Integer.toString(cents));
            price.insert(0, '$');
            price.insert((price.length() - 2), '.');
            if(price.toString().contains("$.")) {
                price.insert(1, '0');
            return price.toString();
        public int convertToCents(String dollars) throws NullPointerException {
            StringBuffer price = new StringBuffer(dollars);
            int index = 0;
            while(index < price.length()) {
                if(Character.isDigit(price.charAt(index)) || price.charAt(index) == '.') {
                    index++;
                else {
                    price.deleteCharAt(index);
            String[] splitPrice = price.toString().split("\\.");
            switch(splitPrice.length) {
                case 1: return (Integer.parseInt(splitPrice[0]) * 100);
                case 2: int convertedPrice = (Integer.parseInt(splitPrice[0]) * 100);
                        if(splitPrice[1].length() <= 2) {
                            convertedPrice += (Integer.parseInt(splitPrice[1]) * (Math.pow(10, (2 - splitPrice[1].length()))));
                            return convertedPrice;
                default: throw new NullPointerException("Incorrect price format");
    }The main methods are input() (basically just a Scanner call; saves typing) and output() (basically a System.out.print call). I'm basically wondering if I can have each instance of this class open a new terminal window (or text window of some sort) where all its outputs will be displayed and all its inputs accepted, without conflicting with other instances of the object.
    Sorry if I'm not being clear. I'm still fairly new to java and the only interactive methods I know are Scanner and print/println :(

  • Unix command Line input and output

    Has anybody used Forte for now window application. Passing values through
    command line and get put as a return value. I am able to call Forte and
    pass input values but I do not know who to get the return value. Here is
    the shell script that I am running:
    #!/bin/csh
    # Ensure that the correct number of parameters were supplied #
    if (${#argv} < 2) then
    then
    echo "USAGE: ecapp Method Number Parm1 Parm2"
    exit 1
    endif
    ftexec -fi bt:$FORTE_ROOT/userapp/mwapp/cl0/mwapp_0 -fnw -fterm $1 $2
    The start class will return a string value after processing the request. I
    can use task.lgr.putline to output to the screen but that is not what I
    would like to do. I want to get the return value assigned to a variable in
    the shell script. One thing I do not know is that if Forte return a string
    that the script can use. Any help would be appreciated.
    thanks in advance
    ka
    Kamran Amin
    Forte Technical Leader, Core Systems
    (203)-459-7362 or 8-204-7362 - Trumbull
    [email protected]
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>

    Hi,
    Did you try to set Task.Part.OperatingSystem.ExitStatus ? But, the ExitStatus is an integer.
    If you really need a string, I would use ExitStatus to know how it finished and an environment variable (Task.Part.OperatingSystem.SetEnv() to position it in your Tool code) to read the string back in the script.
    Hope this helps,
    Daniel Nguyen
    Freelance Forte Consultant
    Url : http://perso.club-internet.fr/dnguyen/

  • How to get COMMAND LINE input

    I am writng an application to add numbers inputted by the user at the command line in a DOS session in the java application. How do i read in input from the user?
    any help is much appreciated

    import java.io.*;
    public class ReadUser {
          static String userInput;
          static int sum = 0;
       public static void main(String[] args) {
          BufferedReader buff = new BufferedReader(new InputStreamReader (System.in));
          // get a string 4 times
          for (int i=0; i<4; i++) {
              System.out.println("Enter a Number");
              try
                   userInput = buff.readLine();
              catch(Exception ex)
                   System.err.println("Had a problem getting input");
                       // convert the string to an int and total it
              sum = sum + Integer.parseInt(userInput);
          // print the sum
         System.out.println("The total is " + sum);
             System.exit(0);

  • Command Line Disk Share with Windows

    I am running Solaris 10 (SunOS 5.10) without the GUI interface. I cannot, therefore, run the Solaris Management Console.
    How do I share my disk with Windows systems on the same network using the command line?

    you can use samba for sharing its comes with solaris 10 , or use solaris 10 as nfs server and use PCNFS on windows end to mount the disk
    in solaris most of things dont require GUI , thats its beauty :)
    regards

  • Line input problem with Logic X, No issues Logic Pro

    I use the line input on my 2011 Imac to record audio from my piano keyboard. When using LOGIC X there is no sound coming through the speakers, but with Logic Pro 9 I have no issues. I tested with new projects, ect but was unable to get to work.
    In both Logic Pro and Logic X I have made an audio track and made sure input monitoring is on. I made sure volume was sufficient. I have tried to fix this to no avail and was thinking about bringing to apple store, but this appreasrs to be some sort of logic x bug (or I am missing something). Any help is appreciated as this is very frustrating.
    Brian

    I think you're missing something.
    http://help.apple.com/logicpro/mac/10/#lgcpbb81aca5
    You have to configure each program top to bottom, go to the above link and make sure all your settings are correct. (the won't necessarily match the pic)
    Look at your Logic 9 settings  Preferences/Audio  and then set up Logic X the same way.

  • Command line - two devices with the same name

    I have two identical logitech usb webcams on the same system,
    and I'm trying to use the command line to encode from each. The
    problem is that the xml profile requires the device name, but both
    devices are listed using the exact same name, so the command line
    only ever chooses one of the cameras as the source. Using the GUI,
    I can select one or the other because they both appear in the drop
    down list.
    Is there a way to specify the device index ala ActionScript,
    or another way to specify the device? I tried renaming the camera
    in the WinXP control panel, but that change was not seen by FME.
    Thanks!

    I'm having the same problem - I tried attaching my Canopus
    ADVC 1000 adapters to different Firewire chains (motherboard and
    PCI-based) but that didn't help.

  • Fail to build SSIS/SSAS projects via VS2012 command line (devenv.exe) with SSDT BI tool installed

    Hello,
    I installed recently released SSDT BI tools for VS2012 and I can work on my existing SSIS/SSAS projects all well in VS2012. But when I try to build my SSIS/SSAS projects via the command line of VS2012, such as
    devenv.exe mySolution.sln /rebuild Release /out "C:\temp\buildLog.txt"
    I will get the error like below in the log file.
    Error: Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))
    Is this a known issue? If yes, any fix has been planned?
    Thanks
    Jimmy

    Hi Jimmy Jin,
    This sounds like .NET framework problem, please refer to:
    http://bchavez.bitarmory.com/archive/2007/08/23/catastrophic-failure-exception-from-hresult-0x8000ffff-e_unexpected.aspx
    http://bchavez.bitarmory.com/archive/2007/08/23/catastrophic-failure-exception-from-hresult-0x8000ffff-e_unexpected.aspx
    Thanks,
    Eileen
    If you have any feedback on our support, please click
    here
    Eileen Zhao
    TechNet Community Support

  • Any command line audio player with song rating and play count?

    Is there any command line audio player that can handle song rating and play count? Thank you

    I answer my question: mpd + mpdcron can store song rating and play count and much more to sqlite database.
    Last edited by hariskar (2015-03-20 05:01:09)

  • Output to command line in Linux with built exe

    Hi Folks,
    Here's an interesting challenge...
    I've got a VI that a customer wants to use as a command line utility in
    Linux.  I've gotten command line arguments in without any
    problem.  However, I can't seem to figure out how to get strings
    back out to the prompt.  The first thing I tried was the system
    exec VI that's in the communication palette.  Is there something
    silly I've overlooked?
    I've also seen some very limited discussion on how to output to the
    command line using Windows API calls.  However, please remember
    that I'm trying to output to the command line in Linux.
    Thanks very much as always.
    Jim

    Hi Jim,
    You can accomplish this using the pipe commands. Just don't open the
    handle, stdout (0), stdin (1), and stderr (2) are always open. See the
    attatched VI.
    For the record, I haven't tried this as an executable, but it works
    running in LabVIEW and I have no reason to expect that it wouldn't work
    as an exe.
    Jason
    Attachments:
    stdout.vi ‏17 KB

  • Command line in Terminal !

    Is there a command or commands that can be ran in the terminal to see if the ethernet port is active or turned off?
    Don
    iMac G5   Mac OS X (10.4.6)  

    Frank,
    It doesn't matter what I plug into the ethernet port on this iMac G5. It won't show anything.
    sidenote: I was having similar problem on my ibook connecting to video camera. I did get a green lite on connecting the camera at the hub. But, not the ibook. After finally getting the IP down right on the ibook. It connected instantly. Right now my ethernet is set to connect automatically without dns servers listed. This works well with airport. If I make new location I have no other option than connect using PPP in the TCP/IP. Now if I can set my IP that might make a difference. I can't. I'm issued a different IP each sign in. When it was working I had dns servers configured. Now when I do that it does not. There might have been something else that got turned on in the process but, I have no idea what it was. And in reality I am not able to connect to anything whether it is a known good cable or device. I can only assume 2 things. The actual port is dead. Or reinstall 10.4.6.

  • Problem opening a file from a command line executed program with args

    I have to run my program from the command prompt like this:
    c:\ java Parser template.txt keyvalue.dat output.txt
    I figured out how to read the args in, and I know they are being assigned to the proper variables. My template.txt, etc are in the same directory that I am in when I run the program. They are also all lowercase, just like the command.
    The only error it throws is the one that I coded (Error opening file template.txt) I would make my message better if I knew what the problem was!!!!
    Any ideas (either for what I'm missing or how to improve my error handling) :\
    Jen

    After catching the exception, call the printStackTrace() to have it print out the error it caught, as well as the file and line number it occured on...

  • Testing Programs that use command line input

    Hi,
    I've written a program that takes values the user enters from the Standard Input (i.e. Dos/UNIX prompt) using the usual buffered reader. I now want to automate testing of this program using a second Java class.
    What is the best way to pass values from the test harness into the program, when it is expecting them from the Standard Input?
    hope someone can help!
    Cheers

    You can also create a new java process with the class you want to test.
    String commandToTest[] = {
    "java", "your.class", ...
    Process process = Runtime.getRuntime().exec( commandToTest );
    InputStream input = process.getInputStream();
    OutputStream output = process.getOutputStream();
    // and then send some input to your sub-process
    //          read the outputIn the same spirit, you can also work with two threads:
    - the first thread reassigns System.in, out and err
    spawns a new Thread that will call your.class.main(...)
    - the first thread sends some input to the new "System.in"
    reads the output from the new "System.out"

  • Command line input

    ...ok, maybe my subject wasn't too good, but say I have two files
    blah.sh and another random program that runs blah.sh
    blah.sh
    #! /bin/bash
    read $1
    print $1
    (or something like that)
    and the other program to run 'blah.sh' and then input (while running) the program something for blah.sh to read?

    skottish wrote:
    zhurai wrote:...ok, maybe my subject wasn't too good
    Yeah, not so good. Please use descriptive thread titles so that others may be able to benefit from this thread.
    not sure exactly what to call it `-`
    HashBox wrote:
    Maybe you mean something like this?
    main.sh
    blah.sh Hello World
    blah.sh
    echo $*
    tested it, but...not really =_=
    zowki wrote:Instead of using examples like blah.sh and main.sh can you give us exactly what you want to accomplish? There may be a better way to do the job.
    well...really I was thinking of if it was possible... but it's like:
    main.sh:
    #! /bin/bash
    ./two.sh
    and
    two.sh:
    #!/bin/bash
    read $1
    print $1
    how exactly would I get main.sh to input something like "Hello World" or whatever message into the read (as in, putting in *that* information w/o user input)
    or however you say it ~_~

Maybe you are looking for