Java Input and Output streams

I have maybe simple question, but I can`t really understand how to figure out this problem.
I have 2 applications(one on mobile phone J2ME, one on computer J2SE). They commuinicate with Input and Output Streams. Everything is ok, but all communication is in sequence, for example,
from mobile phone:
out.writeUTF("GETIMAGE")
getImage();
form computer:
reply = in.readUTF();
if(reply.equals("GETIMAGE")) sendimage()
But I need to include one simple thing in my applications - when phone rings there is function in MIDlet - pauseApp() and i need to send some signal to Computer when it happens. But how can i catch this signal in J2SE, because mayble phone rings when computer is sending byte array? and then suddnely it receives command "RINGING"....?
Please explain how to correcly solve such problem?
Thanks,
Ervins

Eh?
TCP/IP is not a multiplexed protocol. And why would you need threads or polling to decipher a record-oriented input stream?
Just send your images in packets with a type byte (1=command, 2=image, &c) and a packet length word. At the receiver:
int type = dataInputStream.read();
int length = dataInputStream.readInt();
byte[] buffer = new byte[length];
int count, read = 0;
while ((count = dataInputStream.read(buffer,count,buffer.length)) > 0)
read += count;
// At this point we either have:
// type == -1 || count = -1 => EOF
// or count > 0, type >= 0, and buffer contains the entire packet.
switch (type)
case -1:
// EOF, not shown
break;
case COMMAND: // assuming a manifest constant somewhere
// process incoming command
break;
case IMAGE:
// process or continue to process incoming image
break;
}No threads, no polling, and nuthin' up my sleeve.
Modulo bugs.

Similar Messages

  • Java Sockets and Output Streams

    Hi All,
    I am beginning sockets programming and I have a problem. If there is a server listening in the background for incoming connections and say for example 4 client programs programs which we shall call client1...client4 connect. How best can I capture the output streams associated with these newly created sockets so that the server can send back isome nformation to say clients1 and client4 only which is not seen by clients 2 and 3. Similarly I would like the server to send some infor to clients 2 and 3 only which is not seen by client1 and client 4.
    Currently I have the server listening part as shown below, but not too sure how to add DISTINCT output streams for 1 and 4 on one hand and 2 and 3 on the other.
    Thanks:
    // bind socket to a port number
    ServerSocket serverSocket = new ServerSocket(portNo);
    // create socket to listen to client connection
    while (true) {
    //listen to an incoming connection
    System.out.println("chatroom server waiting for incoming connections");
    Socket incomingSocket = serverSocket.accept();
    //launch new thread to take care of new connection
    chatRoomThread chatThread = new chatRoomThread(incomingSocket);
    chatThread.start();
    //go back and wait for next connection
    Please help.
    Thanks,
    Bleak

    HouseofHunger wrote:
    yes thats exactly the way I have my in and out streams, in the run method, but that doesn't help me in filtering traffic, in other words I am saying 2 clients, client1 and client4 for example should share a common in and out stream so that they will see eact other's messages... makes sense.....?No, doesn't make sense. That's the wrong design. Each socket should have its own input and output stream (yes, I know, that's been said several times before). If messages going to client1 should also be sent to client4, then whatever writes the messages to client1's output stream must also write them to client4's output stream. Trying to make those two output streams actually be the same output stream is the wrong way to do that. Just have the controller send the messages to whoever is supposed to get them.

  • MultiThreading with Input and Output Streams

    Hi,
    I have a problem and I think it's because I'm not coding correctly. Please help me if you can understand what I'm doing wrong.
    I have a server that spawns a separate thread to go off and collect data from a serial port. It also waits to accept connections from any client and if a connection is made it will send that data to the clients connected.
    There is data constantly coming in through the serial port. It is output through a DataOutputStream so when the thread is created in the server, I pipe it into a DataInputStream. I do does because I want the server to then read in the data from the inputstream and then send it out to all my clients.
    So far, the way I have it set up seems to do this. But my problem occurs when I try to close a client connection. Instead of removing the socket connection it gives me an error that it can't send data to the client, but it shouldn't be sending data to the client because I just closed it. I realize this is probably because I'm still constantly receiving data from my inputstream and the connection was closed so it can't send that data to the client. I know I need to either close the stream or close my socket but I don't know where this needs to be done. I'm stuck on the correct way to fix this.
    My second problem is the initial connection made to receive data from the inputstream. This is probably because I'm not very familiar with how input/output streams work. But instead of just sending the client the current data being received in real time, it'll send all the data that's buffered in the inputstream. I don't want all the data that's been collecting to go to that first client. I only want the recent data that is coming through while the client is connected. Does this make sense? Because after I make a second client connection I don't have this problem because the InputStream is no longer buffered up. Should I be using something else besides the DataInputStream?
    I feel like I'm going about this the wrong way. Please advise. I'm shy about showing the code but I've included the bulk of it here in hopes that someone will see what I'm doing wrong. The only part that's left out is the thread that reads from the serial port. I don't seem to have any problems with that thread.
    Thanks,
    kim
    ===
    import java.io.*;
    import java.net.*;
    import javax.comm.*;
    import java.util.*;
    // DataServer waits for a client connection
    class DataServer
         static final int PORT = 7;
         // The ServerSocket to use for accepting new connections
         private ServerSocket ss;
         // A mapping from sockets to DataOutputStreams. This will
         // help us avoid from having to create a DataOutputStream each time
         // we want to write to a stream.
         private Hashtable outputStreams = new Hashtable();
         // The inputstream that will receive serial port data through a
         // piped inputstream
         public DataInputStream datalogger;
         // Constructor and while-accept loop all in one.
         public DataServer() throws IOException
              try {
                   // Creating pipe to convert the outputstream from the
                   // RS232 Thread to an inputstream for the server to read
                   PipedOutputStream pout = new PipedOutputStream();
                   PipedInputStream pin = new PipedInputStream(pout);
                   // The inputstream that will receive data from the RS232Thread
                   datalogger = new DataInputStream(pin);
                   // Spawn the thread that will read data through from
                   // the TINI serial port
                   new RS232Thread( pout ).start();
                   // Begin listening for connections and send data
                   listen();
              } catch (IOException ioe) {
                   System.out.println("Error >> DataServer::DataServer()");
                   System.out.println(ioe.getMessage());
                   ioe.printStackTrace();
              } finally {
                   try     {
                        System.out.println( "Closing >> DataServer::DataServer()" );
                        datalogger.close();
                   } catch (IOException i ) {
                        System.out.println( "Error2 >> DataServer::DataServer()" );
                        System.out.println(i); }
         private void listen() throws IOException
              // Create the ServerSocket
              ss = new ServerSocket( PORT );
              // Inform that the server is ready to go
              System.out.println( "Listening on " + ss );
              // Keep accepting connections forever
              while (true) {
                   // Grab the next incoming connection
                   Socket s = ss.accept();
                   // Inform that connection is made
                   System.out.println( "Connection from " + s );
                   // Create a DataOutputStream for writing data to the
                   // other side
                   DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
                   // Save this stream so we don't need to make it again
                   outputStreams.put( s, dout );
                   // Create a new thread for this connection, and then foret
                   // about it
                   new ServerThread( this, s );
         // Get an enumeration of all the OutputStreams, one for each client
         // connected to the server
         Enumeration getOutputStreams() {
              return outputStreams.elements();
         // Send a message to all clients (utility routine)
         void sendToAll( byte[] b ) {
              // synchronize on this because another thread might be
              // calling removeConnection() and this would screw things up
              // while it walks through the list
              synchronized( outputStreams ) {
                   // For each client...
                   for (Enumeration e = getOutputStreams(); e.hasMoreElements();) {
                        // ... get the output stream ...
                        DataOutputStream dout = (DataOutputStream)e.nextElement();
                        // ... and send the message
                        try {          
                             dout.write( b );
                        } catch(IOException ie) {                     
                             System.out.println( "Error >> ServerThread::sendToAll()" );
                             System.out.println( ie );
         // remove a socket, and it's corresponding output stream, from the
         // list. This is usually called by a connection thread that has
         // discovered that the connection to the client is dead.
         void removeConnection( Socket s ) {
              // Synchronize so it doesn't mess up sendToAll() while it walks
              // down the list of all output streams
              synchronized( outputStreams ) {
                   // Inform about removal
                   System.out.println( "Removing connection to " + s );
                   // Remove if from our hastable/list
                   outputStreams.remove( s );
                   // Make sure it's closed
                   try {
                        s.close();
                   } catch( IOException ie ) {
                        System.out.println( "Error closing " + s );
                        ie.printStackTrace();
         // main - Opens a server socket and spins off a new thread each time
         // a new client connection is accepted on this socket.
         public static void main(String[] args) throws Exception
              System.out.println("Starting DataServer version 1.0 ...");
              try     
                   new DataServer();
              catch (IOException ioe)
                   System.out.println( "Error >> DataServer::main()" );
                   System.out.println(ioe.getMessage());
                   ioe.printStackTrace();
    class ServerThread extends Thread
         //The Server that spawned this thread
         private DataServer server;
         // The Socket connected to the client
         private Socket socket;
         //Constructor
         public ServerThread( DataServer server, Socket socket )
              // save the parameters
              this.server = server;
              this.socket = socket;
              // Start up the thread
              start();
         // This runs in a separate thread when start() is called in the
         // constructor
         public void run() {
              try {
                   // The inputstream receiving data from the global inputstream
                   // that is piped to the RS232 Thread
                   // ???? is this where i'm messing up ???
                   DataInputStream in = new DataInputStream( server.datalogger );
                   int num = 0;
                   byte[] d = new byte[1];
                   // read from the inputstream over and over, forever ...
                   while( ( num = in.read(d) ) > 0 ) {
                        // ... and have the server send it to all clients
                        server.sendToAll( d );               
              } catch (IOException ioe) {
                   System.out.println( "Error >> ServerThread::run()" );
                   System.out.println(ioe.getMessage());
                   ioe.printStackTrace();
              } finally {
                   // The connection is closed for one reason or another,
                   // so have the server dealing with it
                   System.out.println( "Closing" );
                   server.removeConnection( socket );

    A couple of things to note...
    First, you are looping infinitely in your server's constructor. Since the constructor is never completing, your server object is never completely constructed - this may cause indeterminate behaviour when you pass a reference to the server to another thread.
    Second, I would recommend fixing your issues by modifying your design somewhat. The design I would recommend (read: The design I would use) is:
    A server object, with a public listen method. The constructor spawns a thread to constantly read from the serial port and forward the data read back to the server, via a multicast (sendToAll) method.
    The listen method sets up a server socket to accept connections, and in a loop opens client sockets and stores them in a set.
    The multicast method iterates through the list of open client sockets, and for each in turn confirms that it is still open. If open, send the data down the socket's output stream; if closed, remove the socket from the set.
    Note that this design includes only two threads - the main thread listens for and accepts new socket connections, while the extra thread collects data from the serial port, multicasts it to all of the open sockets, and removes all of the closed sockets. If you require to perform any other communication with the sockets, it may be necessary to create a thread for those sockets, to facilitate reading from their input streams, but in the given design, this is not necessary.
    I hope this helps,
    -Troy

  • Pipes (Input- and Output-streams) to a Process are not closed

    Hello experts!
    I have a long-living server-process that opens external programs with
    Runtime.getRuntime().exec() all the time. For communication with one
    of the external program I use stdin and stdout. I close all streams in
    finally-blocks, so there should not be any open stream.
    The problem is, that most of the time the used streams are closed
    correctly. But sometimes some of them left open. I check that with
    the linux command-line tool lsof. So over time the number of open
    pipes increases and eat up all file-handles till an IOException (too
    many open files) is thrown.
    If I watch the -verbosegc output, I see that most of the open pipes
    are cleaned up after a GC-run. But over time - not all.
    I start the external program in a thread, what could explain that
    it happens only sometimes.
    I'm hunting this bug now for quite a long time. Are there any known
    problems with using pipes to/from other processes (under linux?)
    thanks
    lukas

    Hi!
    Now I did some heavy logging and I saw that the remaining pipes are the ones I DON'T
    open to read or write! No joke! For example - for one process I don't read or write any of
    stdin,stdout,stderr - then in one of X executions all three pipes are left open (shown by
    lsof for the java-process, after many GC-runs).
    To test it I read the stdin of this process - then this stream was closed in the error case,
    but stdout and stderr are still open. This is really strange!
    anybody seen this before?
    lukas

  • Input and output streams

    I am struggling with this, if any of you have any advice I would appreciate it.
    I am creating a java server that can communicate with a client over tcp sockets and to a device through a serial port. I have have the TCP part all set up. I found this packet and code to be able to communicate through a serial port.
    http://rxtx.qbang.org/wiki/index.php/Two_way_communcation_with_the_serial_port
    it works by itself, but I don't think I can make it work with my server because I am already using a system.in for the tcp portion of it. In the long run what I want to be able to do is take information from the socket connection, play with it a little bit, and then send it out the serial port to the device.
    Is it possible to convert this code to instead of asking for input from the keyboard, to take a string that I can pass in from somewhere, or if something comes in on the serial port to write it to a string or something?

    Sorry I was so vague.
    this code that i found on the website, creates a connection with the serial port, then it waits for input from the keyboard. once that input comes in, it sends out that stuff through the serial port. I want it to instead of wanting for input from the keyboard, to check to see if there is something in a string or something, if there is write it out to the serial port.
    Basically instead of having a listener constantly waiting for input from the keyboard, be able to call a method from the rest of my program to send stuff out the serial port.

  • Input and Output Stream conversion

    I have problem. In my application I should change OutputStream to InputStream and vv. I try to explain it using easy example.
    I am creatin xml document and using XMLOutputter (I am using org.jdom parser) I could write it to file using FileOutputStream, but first I'd like to encrypt this file. For that reason I need InputStream. I write this file on disc, next i read this file, encrypt and write again and at last delete the unencrypted file. Could do It without writeing unencrypted file on disc? Maybe using only streams? Pleas help me, how to do it. Maybe I should convert OutputStream to InputStream.
    When I reading information from encrypted file I have the same problem - streams conversion.

    I wrote an article about how to convert an OutputStream to an InputStream. You can read the article at:
    http://ostermiller.org/convert_java_outputstream_inputstream.html
    It discusses three methods for conversion: byte arrays, piped streams, and circular buffers.

  • Synchronize input and output tasks to start at the same sample point [C++ NI_DAQmx Base]

    I'm trying to initiate the analog input and output streams to start reliably at the same sample. I've tried triggering the output from the start of the input using the following code [NI-DAQmx Base 2.1 under Mac OS X with an M-Series multifunction board]. It compiles and runs, but gives an error message at the call to "DAQmxBaseCfgDigEdgeStartTrig". Any suggestions about synchronized I/O on this platform?
    #include "NIDAQmxBase.h"
    #include
    #include
    #include
    #define DAQmxErrorCheck( functionCall ) { if ( DAQmxFailed( error=( functionCall ) ) ) { goto Error; } }
    int main( int argc, char *argv[] )
    // Task parameters
    int32 error = 0;
    TaskHandle inputTaskHandle = 0;
    TaskHandle outputTaskHandle = 0;
    char errorString[ 2048 ] = {'\0'};
    int32 i;
    time_t startTime;
    // input channel parameters
    char inputChannelList[] = "Dev1/ai0, Dev1/ai1";
    float64 inputVoltageRangeMinimum = -10.0;
    float64 inputVoltageRangeMaximum = 10.0;
    // output channel parameters
    char outputChannelList[] = "Dev1/ao0, Dev1/ao1";
    char outputTrigger[] = "Dev1/ai/StartTrigger";
    float64 outputVoltageRangeMinimum = -10.0;
    float64 outputVoltageRangeMaximum = 10.0;
    // Timing parameters
    char clockSource[] = "OnboardClock";
    uInt64 samplesPerChannel = 100000;
    float64 sampleRate = 10000.0;
    // Input data parameters
    static const uInt32 inputBufferSize = 100;
    int16 inputData[ inputBufferSize * 2 ];
    int32 pointsToRead = inputBufferSize;
    int32 pointsRead;
    float64 timeout = 10.0;
    int32 totalRead = 0;
    // Output data parameters
    static const uInt32 outputBufferSize = 1000;
    float64 outputData[ outputBufferSize * 2 ];
    int32 pointsToWrite = outputBufferSize;
    int32 pointsWritten;
    for( int i = 0; i < outputBufferSize; i++ )
    outputData[ 2 * i ] = 9.95 * sin( 2.0 * 3.14159 * i / outputBufferSize );
    outputData[ 2 * i + 1 ] = -9.95 * sin( 2.0 * 3.14159 * i / outputBufferSize );
    // ------------------- configure input task -----------------------
    DAQmxErrorCheck ( DAQmxBaseCreateTask( "", &inputTaskHandle ) );
    printf( "Created input task\n" );
    DAQmxErrorCheck ( DAQmxBaseCreateAIVoltageChan( inputTaskHandle, inputChannelList, "", DAQmx_Val_RSE, inputVoltageRangeMinimum, inputVoltageRangeMaximum, DAQmx_Val_Volts, NULL ) );
    printf( "Created AI Voltage Chan\n" );
    DAQmxErrorCheck ( DAQmxBaseCfgSampClkTiming( inputTaskHandle, clockSource, sampleRate, DAQmx_Val_Rising, DAQmx_Val_ContSamps, samplesPerChannel ) );
    printf( "Set sample rate\n" );
    // ------------------- configure output task -----------------------
    DAQmxErrorCheck ( DAQmxBaseCreateTask( "", &outputTaskHandle ) );
    printf( "Created output task\n" );
    DAQmxErrorCheck ( DAQmxBaseCreateAOVoltageChan( outputTaskHandle, outputChannelList, "", outputVoltageRangeMinimum, outputVoltageRangeMaximum, DAQmx_Val_Volts, NULL ) );
    printf( "Created AO Voltage Chan OK\n" );
    DAQmxErrorCheck ( DAQmxBaseCfgSampClkTiming( outputTaskHandle, clockSource, sampleRate, DAQmx_Val_Rising, DAQmx_Val_ContSamps, samplesPerChannel ) );
    printf( "Set sample rate\n" );
    // trigger output when input starts
    DAQmxErrorCheck ( DAQmxBaseCfgDigEdgeStartTrig( outputTaskHandle, outputTrigger, DAQmx_Val_Rising ) );
    printf( "Set output trigger\n" );
    // ------------------- configuration -----------------------
    // write output signal
    DAQmxErrorCheck ( DAQmxBaseWriteAnalogF64( outputTaskHandle, pointsToWrite, 0, timeout, DAQmx_Val_GroupByScanNumber, outputData, &pointsWritten, NULL ) );
    printf( "Write output signal\n" );
    // set up input buffer
    DAQmxErrorCheck ( DAQmxBaseCfgInputBuffer( inputTaskHandle, 200000 ) ); // use a 100,000 sample DMA buffer
    // initiate acquisition - must start output task first
    DAQmxErrorCheck ( DAQmxBaseStartTask( outputTaskHandle ) );
    DAQmxErrorCheck ( DAQmxBaseStartTask( inputTaskHandle ) );
    // The loop will quit after 10 seconds
    Dr John Clements
    Lead Programmer
    AxoGraph Scientific

    Hi Michael,
    First of all, thanks very much for taking the time to investigate this problem! Much appreciated.
    You asked for "an actual error code you got and any description that is given". The full output from the program that I posted earlier in this thread is appended to the end of this message. In summary, following the call to...
    DAQmxErrorCheck ( DAQmxBaseCfgDigEdgeStartTrig( outputTaskHandle, outputTrigger, DAQmx_Val_Rising ) );
    ... with ...
    char outputTrigger[] = "Dev1/ai/StartTrigger";
    ...the error message is ...
    DAQmxBase Error: Specified route cannot be satisfied, because the hardware does not support it.
    You asked "specifically which M series device you are using"? It is the PCIe 6251 (with BNC 2111 connector block). I'm testing and developing on an Intel Mac Pro (dual boot OS X and Windows XP).
    You asked for "the location you pulled the code from". Here it is...
    http://zone.ni.com/devzone/cda/epd/p/id/879
    ...specifically from the file "Multi-Function-Synch AI-AO_Fn.c".
    I adapted the NI-DAQmx calls to their NI-DAQmx Base equivalents.
    Finally, you asked "Is the trigger necessary, or do you just need to know that the measurements are running on the same clock?". I believe that some kind of sychronized trigger is necessary in my situation (correct me if I'm wrong). Timing is crucial. Say I initiate an analog output stream that delivers a voltage command step 5 ms from the onset. I need to record the response (analog input stream) so that its onset is accurately aligned (synchronized) at 5 ms. A typical recording situation would stimulate and record a short data 'sweep', then wait for the (biological) system to recover, then stimulate and record another short sweep, and repeat. I need all the recorded sweeps to align accurately so that they can be averaged and analyzed conveniently.
    I definitely do not want my customers to rely on an expensive external TTL pulse generator to initiate and synchronize each 'sweep'. That would effectively eliminate the cost advantage of an NI board, as well as adding unnecessary complexity in setup and use. It would be a show-stopper for me.
    It seems perverse, but would it be possible to use a digital output channel connected directly to a digital input chanel to trigger the input and output streams?
    Regards,
    John.
    Full output from test program. Compiled with gcc 4 under OS X...
    [Session started at 2007-05-23 14:17:01 +1000.]
    LoadRuntime: MainBundle
    CFBundle 0x303cc0 (executable, loaded)
    _CompatibleWithLabVIEWVersion: linkedAgainst: 08208002
    _CompatibleWithLabVIEWVersion: result= false, mgErr= 1, theActualVersion= 00000000
    _CompatibleWithLabVIEWVersion: linkedAgainst: deadbeef
    _CompatibleWithLabVIEWVersion: Reseting Linked Against
    _CompatibleWithLabVIEWVersion: linkedAgainst: 08208002
    _CompatibleWithLabVIEWVersion: result= true, mgErr= 0, theActualVersion= 00000000
    _CompatibleWithLabVIEWVersion: linkedAgainst: 08208002
    _CompatibleWithLabVIEWVersion: result= true, mgErr= 0, theActualVersion= 00000000
    com.ni.LabVIEW.dll.nidaqmxbaselv
    CFBundle 0x313760 (framework, loaded)
    {type = 15, string = file://localhost/Library/Frameworks/nidaqmxbaselv.framework/, base = (null)}
    Amethyst:Library:Frameworks:nidaqmxbaselv.framework
    2007-05-23 14:17:02.248 test-ni[4445] CFLog (21): Error loading /Library/Frameworks/LabVIEW 8.2 Runtime.framework/resource/nitaglv.framework/nitaglv: error code 4, error number 0 (no suitable image found. Did find:
    /Library/Frameworks/LabVIEW 8.2 Runtime.framework/resource/nitaglv.framework/nitaglv: mach-o, but wrong architecture)
    CFBundle 0x1751fdc0 (framework, not loaded)
    Created input task
    Created AI Voltage Chan
    Set sample rate
    Created output task
    Created AO Voltage Chan OK
    Set sample rate
    DAQmxBase Error: Specified route cannot be satisfied, because the hardware does not support it.
    test-ni has exited with status 0.
    Dr John Clements
    Lead Programmer
    AxoGraph Scientific

  • Separate thread for input stream and output stream.

    Hi Techies,
    In a socket connection, can we run the input stream and output stream in separate threads. actually in my case, the input stream will be getting the input regularly and output stream will send data very rare. so if i impelment them in one class then unless there is data to send output stream will be blocked. i was thinking to impelment both the streams in separate threads. is it a good way? so how to implement it. your guidance will be of great help.
    thanks in advance.

    JavaBreather wrote:
    Hi Techies,
    In a socket connection, can we run the input stream and output stream in separate threads.I would say this is the most common way of handling sockets and threads. esp pre-NIO.
    Iis it a good way? so how to implement it. your guidance will be of great help.Once you have a socket, create two threads, one which does the reading and one which does the writing.
    You could use BlockingQueues to abstract access to these threads. i.e. the reading thread reads something from the socket and adds it to the BlockingQueue. The writing thread take()s something froma second BlockingQueue and writes it to the Socket. This way you add things to write or get thing to process by looking at the BlockingQueues.

  • How to control (the input and output) EXE file after I call it using exec?

    Hi,
    I knew that I can use runtime.exec() to call one EXE file, and this works. But this EXE has two characteristics:
    1. After this exe starts, it asks user to input number such as 1 or 2 onto computer screen, then press return. Then the exe will start the calculation.
    2. after it starts calculation, it prints 3 columns of numbers onto the screen.
    My two questions are:
    1. How to use java to input the number such as 1 or 2 automatically? this EXE can not work like this in DOS command line:
    C:> file.exe parameter
    The parameter is the number such as 1 or 2 that I wanna input.
    2. how to redirect the 3 columns of numbers from computer screen to txt file?
    My colleague can solve these two questions using Mathematica. So I know that definitely there is at least one solution for it. I just can not do it using Java. This wierd exe file bothered me a lot and I really wish that I can get help from someone in java community.
    Thank you!
    Tony

    When you call Runtime.exec, you get a Process object. (I presume something similar happens when you use ProcessBuilder.) Process has methods with names getOutput, getInput, and getError. These correspond to the standard input, standard output, and standard error streams of the spawned process.
    You can read and write to the process on the streams corresponding to input and output that the process writes to the console.
    [add]
    In fact, you should be grabbing and reading the output/error streams anyway, because of the points raised by the Traps article. Google "Java Runtime exec traps" and you'll probably get a link to this JavaWorld article, which describes common Runtime.exec problems and how to solve them.
    Edited by: paulcw on Jun 15, 2010 4:09 PM

  • Fileinput and output stream

    hi. i was trying to learn this fileinput and output stream in java. i was trying to solve this exercise problem in which a user need to ask for the inputfile (Which i have created mydata.txt which has 5 positive numbers and 5 negative numbers ). my program will ask the user for the input file and then output the results in 2 seperate files one output will be for positive integers which the program will extract from myData,txt and negative integers to another output file. i am very confused. my program does not give me any error msgs but outputs a number 0.
    import java.util.Scanner;
    import java.io.*;
    class fileEg {
         public static void main (String[] args) throws IOException
         int num=0, num1;
         Scanner user = new Scanner(System.in);
         String inputFileName, outputFileName, fileName;
         System.out.println("Input File Name ");
         inputFileName = user.nextLine().trim();
         File input = new File (inputFileName);
         Scanner scan = new Scanner(input);
         System.out.print("Output File Name: ");
        outputFileName = user.nextLine().trim();
        File output = new File( outputFileName );     
        PrintStream  print = new PrintStream( output );     
        while(scan.hasNextInt()) {
             if(num == '+') {
                  print.println( "the numbers are " + num);
             else {
                  print.println("The numbers ares " + num);
             print.close();
    }any help will be really appreciated. any theories or example.
    Thanks

    import java.util.Scanner;
    import java.io.*;
    class fileEg {
         public static void main (String[] args) throws IOException
         int num;
         Scanner user = new Scanner(System.in);
         String inputFileName, outputFileName, negativeFileName;
         System.out.println("Input File Name ");
         inputFileName = user.nextLine().trim();
         File input = new File (inputFileName);
         Scanner scan = new Scanner(input);
         System.out.print("Output File positive Name: ");
        outputFileName = user.nextLine().trim();
        File output1 = new File( outputFileName );     
        PrintStream  positiveNumbers = new PrintStream( output1 ); 
        System.out.print("Output File negative Name: ");
        negativeFileName = user.nextLine().trim();
        File output = new File( negativeFileName );     
        PrintStream  negativeNumbers = new PrintStream( output ); 
    while(scan.hasNextInt()) {
             num= scan.nextInt();
             if (num >0) {
                  positiveNumbers.println( "the numbers are " + num);
             } else {
                  negativeNumbers.println("The numbers ares " + num);
    positiveNumbers.close();
    negativeNumbers.close();
    }Thanks paul
    Message was edited by:
    fastmike

  • FINALLY INPUTTING and OUTPUTTING Annotations!

    Ok, before everyone thinks that this is a very bad solution, I have to tell that I`m no programmer and my knowledge of PostgreSQL, Ruby or any other language is very poor.
    With useful help from Jamie Hodge, fbm and Nicholas Stokes (mainly)
    I could manage to write a command for inputting and outputting from Final Cut Server Annotations.
    So lets go to the fun part:
    INPUTTING:
    1- Create a Response called "Annotations IN" (or whatever you want):
    a - Reponse Action: "Run an external script or command"
    b - Run Script > *Commnad Path: /Library/Application Support/Final Cut Server/Final Cut Server.bundle/Contents/Resources/sbin/fcsvr_run
    Command Parameters: psql px pxdb -c "COPY pxtcmdvalue FROM '/FCSRV/annotation-in.txt' USING DELIMITERS '|';"
    2 - Create a poll Watcher with name: "Watch for Annotations IN"
    a - Enable: true
    b - Monitor Address: Chooses a Device (create a new one or use a tmp one) and path to where you`ll going to put a txt file with the annotations.
    c - Response List: Choose the Response you created "Annotations IN" in my case.
    d - Event Type Filter: Created, Modified
    e - Poll Watcher > Listing Frequency: 2 (or any number of seconds you feel like it).
    Listing multiple: 2
    Wildcard include Filter: *.txt (or any custom extensions you want)
    3 - Create a txt file and use this as a template:
    {ASSET_ENTITYID}|1527|{TCIN}/(30000,1001)|{TCOUT}/(30000,1001)|{Annotation}|{USE RID}|{DATE}
    Where:
    {ASSET_ENTITYID} = Is the entityid of your asset. You can find what number it is by issuing:
    /Library/Application\ Support/Final\ Cut\ Server/Final\ Cut\ Server.bundle/Contents/Resources/sbin/fcsvr_run psql px pxdb -c "SELECT pxmdvalue.entityid, pxmdvalue.value AS asset_name FROM pxmdvalue INNER JOIN pxentity ON pxentity.entityid = pxmdvalue.entityid WHERE pxmdvalue.fieldid='1543' AND pxentity.address LIKE '/asset/%';"
    This will output ALL your assets, so if you know the name or want to parse the name you can use:
    /Library/Application\ Support/Final\ Cut\ Server/Final\ Cut\ Server.bundle/Contents/Resources/sbin/fcsvr_run psql px pxdb -c "SELECT pxmdvalue.entityid, pxmdvalue.value AS asset_name FROM pxmdvalue INNER JOIN pxentity ON pxentity.entityid = pxmdvalue.entityid WHERE pxmdvalue.fieldid='1543' AND pxmdvalue.value='ASSETNAME' AND pxentity.address LIKE '/asset/%';"
    Where in ASSETNAME you`ll have to put your Asset Name without extension.
    {TCIN} and {TCOUT} is, of course, the TC`s points. In the form of: HH:MM:SS;FF
    {Annotation} is the commentary.
    {USERID} (in my case was 1)
    {DATE}: This one is tricky. My example is 2009-03-15 19:31:15.839795-03
    So is in the form YYYY-MM-DD HH:MM:SS.????? I really don`t know the rest. Could be milliseconds?
    Of course one can write a script to translate everything from a txt file like:
    ASSETNAME | TCIN | TCOUT | ANNOTATIONS | USER
    But as I`ve said I`m no programmer
    Ok.. now the time for the OUTPUT:
    The command-line is:
    /Library/Application\ Support/Final\ Cut\ Server/Final\ Cut\ Server.bundle/Contents/Resources/sbin/fcsvr_run psql px pxdb -c "SELECT pxmdvalue.value AS Asset_NAME, pxtcmdvalue.value, pxtcmdvalue.begintc, pxtcmdvalue.endtc FROM pxmdvalue INNER JOIN pxtcmdvalue ON pxmdvalue.entityid = pxtcmdvalue.entityid WHERE pxmdvalue.value='ASSETNAME';"
    Where ASSETNAME is the Asset name without the extension.
    Or issuing the following to OUTPUT ANNOTATIONS from ALL assets:
    /Library/Application\ Support/Final\ Cut\ Server/Final\ Cut\ Server.bundle/Contents/Resources/sbin/fcsvr_run psql px pxdb -c "select * from pxtcmdvalue;"
    Adding "> /PATHTO_WHERE_IN_WANT/ANNOTATIONSOUTPUT.TXT" at the end will put all output into a txt file.
    It`s possible (in theory) to:
    1- Create a boolean md field in FCSRV called "EXPORT Annotations" (don`t choose lookup)
    2- add or create a md group called "Export Annotations" and add the above md field to it (don`t choose lookup)
    3- Add "Export Annotations" md field to Asset Filter md group
    4- Make a Response for Running external command. Command path: /Library/Application Support/Final Cut Server/Final Cut Server.bundle/Contents/Resources/sbin/fcsvr_run
    Command Parameters: psql px pxdb -c 'SELECT pxmdvalue.value AS Asset_NAME, pxtcmdvalue.value, pxtcmdvalue.begintc, pxtcmdvalue.endtc FROM pxmdvalue INNER JOIN pxtcmdvalue ON pxmdvalue.entityid = pxtcmdvalue.entityid WHERE pxmdvalue.value=[FileName];' > ~/Desktop/ann-out.txt
    (I`m having problem with this, it doesn`t work).
    5- Make a Subscription that if Export Annotations modified = true, trigger if changed and trigger the Response above.
    6- Add exporting annotations md group to Media md set.
    In theory it`s possible to modify the FinalCutServerIntegrationSample get and input annotations instead of adding another "comment" field to md group list.
    Few!
    Ok so please help beautify this out!
    This will be very useful for a lot of people.... We know that it`s only a matter of time to FCSVR have this function built-in... but this "time" could be years.
    So let`s start ourselves!
    Thank you very much!!
    Regards!

    AlphaBlue wrote:
    jverd wrote:
    What were you hoping for? Someone reading your mind for what exactly you need, and handing you a giftwrapped answer, without you doing any work or clearly communicating a specific problem? This site doesn't really work that way.Fair enough. I'm asking for insight into how to input from and output to a StarOffice Spreadsheet into/from a Java program. (Think java.io except with spreadsheet files instead of .txt files.) I already answered that question.
    I need to accomplish this without the use of a community-created library.That's a bizarre requriement. Why?
    >
    Okay, [here you go|http://lmgtfy.com/?q=communication+between+StarOffice+Spreadsheets+and+Java].
    If you don't have any knowledge or experience, on the matter, please refrain from directing me to a google search. I assure you, I have already performed such a task.How would I know that.
    But okay, let's say I know that. Let's say you bothered to point out that you've already done that. Further, let's say I do have knowledge of the subject at hand. Maybe I'm an expert. Maybe I wrote Star Office and an open source library (which wheel for some reason you must reinvent). You are assuming that I also have psychic powers, so that I can read your mind and know exactly what you've read so far and exactly what parts of your very broad and vague question said reading did not answer.
    In short, you have received answers commensurate with your questions.

  • XSLT Generation from input and output XML

    Is it possible to generate an XSL mapping file in Java if we have input and output XML.
    If yes, then how to achieve this when user defined functions are used during mapping?

    Hi Prateek,
    check the following links for Business connectors and adapter:
    http://help.sap.com/saphelp_nw2004s/helpdata/en/92/3bc0401b778031e10000000a1550b0/frameset.htm
    http://help.sap.com/saphelp_nw2004s/helpdata/en/2c/4fb240ac052817e10000000a1550b0/frameset.htm
    http://help.sap.com/saphelp_nw2004s/helpdata/en/6a/3f93404f673028e10000000a1550b0/frameset.htm
    Hope these help you.
    Regards,
    Anuradha.B

  • Simple input and output in a loop

    I'm trying to get some user input in a loop. This is a simplification.
    import java.util.Scanner;
    public class Main {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            for (int i = 0; i < 3; i++) {
                System.out.println("Enter a string:");
                String myString = input.nextLine();
                System.out.println("output: " + myString);
    }In NetBeans, it usually runs fine for a few loops, but eventually (running the program 5 times or so) I get output like this:
    run:
    Enter a string:
    1
    output: 1
    Enter a string:
    output: 2
    Enter a string:
    2
    3
    output: 3
    BUILD SUCCESSFUL (total time: 9 seconds)It starts writing the prompt before the output and gets all jumbled. The problem is worse if I have more input and output statments in the loop. I thought it might just be a timing issue, but it doesn't matter how fast or slow I enter the information. After a few successive runs, the output always gets out of order. How can I keep in line?

    hi!
    why dont you try using printf it will give you a better formating capasities.
    it work like this.
    import java.util.Scanner;
    public class Main {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            for (int i = 0; i < 3; i++) {
                System.out.println("Enter a string:");
                String myString = input.nextLine();
                System.out.printf("output: %s  \n" ,  myString );  // the %s is the place the string will apear
                                                                                       //and the \n is a escape caracter that creates a new line.
    }if you need more help with printf read this:
    http://en.wikipedia.org/wiki/Printf

  • Wrong input and output files path?

    When i tried to run my code i got wrong path of input and output files, why it was and where is the mistake? I did not meant the path \tmp\xorout.txt and C:\jar\org\joone\samples\engine\xor\xor.txt in the source code - where are they from? :
    * XOR.java
    * Sample class to demostrate the use of the Joone's core engine
    * see the Developer Guide for more details
    * JOONE - Java Object Oriented Neural Engine
    * http://joone.sourceforge.net
    package org.joone.samples.engine.xor;
    import java.io.File;
    import org.joone.engine.*;
    import org.joone.engine.learning.*;
    import org.joone.io.*;
    import org.joone.net.NeuralNet;
    public class XOR implements NeuralNetListener {
    /** Creates new XOR */
    public XOR() {
    * @param args the command line arguments
    public static void main() {
    XOR xor = new XOR();
    xor.Go();
    public void Go() {
    * Firts, creates the three Layers
    LinearLayer input = new LinearLayer();
    SigmoidLayer hidden = new SigmoidLayer();
    SigmoidLayer output = new SigmoidLayer();
    input.setLayerName("input");
    hidden.setLayerName("hidden");
    output.setLayerName("output");
    /* sets their dimensions */
    input.setRows(2);
    hidden.setRows(3);
    output.setRows(1);
    * Now create the two Synapses
    FullSynapse synapse_IH = new FullSynapse(); /* input -> hidden conn. */
    FullSynapse synapse_HO = new FullSynapse(); /* hidden -> output conn. */
    synapse_IH.setName("IH");
    synapse_HO.setName("HO");
    * Connect the input layer whit the hidden layer
    input.addOutputSynapse(synapse_IH);
    hidden.addInputSynapse(synapse_IH);
    * Connect the hidden layer whit the output layer
    hidden.addOutputSynapse(synapse_HO);
    output.addInputSynapse(synapse_HO);
    FileInputSynapse inputStream = new FileInputSynapse();
    /* The first two columns contain the input values */
    inputStream.setAdvancedColumnSelector("1,2");
    /* This is the file that contains the input data */
    inputStream.setInputFile(new File("c:\\xor.txt"));
    input.addInputSynapse(inputStream);
    TeachingSynapse trainer = new TeachingSynapse();
    /* Setting of the file containing the desired responses,
    provided by a FileInputSynapse */
    FileInputSynapse samples = new FileInputSynapse();
    samples.setInputFile(new File("c:\\xor.txt"));
    /* The output values are on the third column of the file */
    samples.setAdvancedColumnSelector("3");
    trainer.setDesired(samples);
    /* Creates the error output file */
    FileOutputSynapse error = new FileOutputSynapse();
    error.setFileName("c:\\xorout.txt");
    //error.setBuffered(false);
    trainer.addResultSynapse(error);
    /* Connects the Teacher to the last layer of the net */
    output.addOutputSynapse(trainer);
    NeuralNet nnet = new NeuralNet();
    nnet.addLayer(input, NeuralNet.INPUT_LAYER);
    nnet.addLayer(hidden, NeuralNet.HIDDEN_LAYER);
    nnet.addLayer(output, NeuralNet.OUTPUT_LAYER);
    nnet.setTeacher(trainer);
              FileOutputSynapse results = new FileOutputSynapse();
    results.setFileName("c:\\results.txt");
    output.addOutputSynapse(results);
    // Gets the Monitor object and set the learning parameters
    Monitor monitor = nnet.getMonitor();
    monitor.setLearningRate(0.8);
    monitor.setMomentum(0.3);
    /* The application registers itself as monitor's listener
    * so it can receive the notifications of termination from
    * the net.
    monitor.addNeuralNetListener(this);
    monitor.setTrainingPatterns(4); /* # of rows (patterns) contained in the input file */
    monitor.setTotCicles(2000); /* How many times the net must be trained on the input patterns */
    monitor.setLearning(true); /* The net must be trained */
    nnet.go(); /* The net starts the training job */
    public void netStopped(NeuralNetEvent e) {
    System.out.println("Training finished");
    public void cicleTerminated(NeuralNetEvent e) {
    public void netStarted(NeuralNetEvent e) {
    System.out.println("Training...");
    public void errorChanged(NeuralNetEvent e) {
    Monitor mon = (Monitor)e.getSource();
    /* We want print the results every 200 cycles */
    if (mon.getCurrentCicle() % 200 == 0)
    System.out.println(mon.getCurrentCicle() + " epochs remaining - RMSE = " + mon.getGlobalError());
    public void netStoppedError(NeuralNetEvent e,String error) {
    ERROR:
    C:\jar>java -cp joone-engine.jar org.joone.samples.engine.xor.XOR C:\\xor.txt C:
    \\xorout.txt
    [main] [ERROR] - org.joone.io.FileOutputSynapse - IOException in Synapse 6. Mess
    age is : \tmp\xorout.txt (The system cannot find the path specified)
    Training...
    [Thread-0] [WARN] - org.joone.io.FileInputSynapse - IOException in Synapse 3. Me
    ssage is : C:\jar\org\joone\samples\engine\xor\xor.txt (The system cannot find t
    he path specified)
    [Thread-0] [WARN] - org.joone.io.FileInputSynapse - IOException in Synapse 3. Me
    ssage is : C:\jar\org\joone\samples\engine\xor\xor.txt (The system cannot find t
    he path specified)
    java.lang.NullPointerException
    at org.joone.io.StreamInputSynapse.getStream(StreamInputSynapse.java:176
    at org.joone.io.StreamInputSynapse.readAll(StreamInputSynapse.java:288)
    at org.joone.io.StreamInputSynapse.fwdGet(StreamInputSynapse.java:106)
    at org.joone.engine.Layer.fireFwdGet(Layer.java:212)
    at org.joone.engine.Layer.fwdRun(Layer.java:1225)
    at org.joone.net.NeuralNet.stepForward(NeuralNet.java:1015)
    at org.joone.net.NeuralNet.fastRun(NeuralNet.java:970)
    at org.joone.net.NeuralNet.fastRun(NeuralNet.java:937)
    at org.joone.net.NeuralNet$1.run(NeuralNet.java:890)
    at java.lang.Thread.run(Thread.java:534)

    c:xor.txt
    c:/xor.txt
    i think c:xor stands for somthing else like a virtual drive but ima not sure

  • Java.lang.IllegalStateException : output stream already retrived Error

    Hi All
    I am trying to integrate crystal reports 10g with oracle 10g AS.My application works fine on TOMCAT 4.1.31,but when I depoly in oracle 10G AS,it shows the following exception
    Java.lang.IllegalStateException : output stream already retrived.
    Any suggestions?
    Regards
    Mohan

    Hello,
    Awaiting help.
    Thanks and Regards
    Mohan

Maybe you are looking for

  • Limitation Importing Photos from Iphoto to Iphone

    I have over 28,000 photos on an external drive and want to import just selected photos, individual from there to my Iphone. In Itunes, I have the option to Sync Photo from Iphoto, or I can choose to sync from a specific folder. If I pick Iphoto, I th

  • Can any one help me? My os x 10.4.11 will not update to 10.5 it just won't show up!!!

    I'm so confused i cannot get my computer to update past 10.4.11

  • Improve Arabic Language Z10

    Hey What's app guys .,  we have problem in Arabic language in Z10  it's small buttons it's made it hard touched and there some characters is missing  like ( ُ  ) and ( ٌ  ) so we made a ned keyboard to Z10 it's better  i don't know u guys can making

  • Tab view in Safari

    OK - sorry if this has been asked and answered - can't seem to find it. Just updated to iOS7 (iPad2) and in Safari - I don't see a menu bar at the bottom of the screen. When I hit the add tab, I do have a menu that appears - but it only has private i

  • Sizing down the library folder.

    I have had this install of OSX tiger on my MacBook Pro for quite some time now and have added and removed many applications. Currently I have very few applications left after I uninstalled all of the programs I don't use. I now have less than 6 Gigs