Reading an input stream
Work on JDE 4.2.1
My requirement is to combine a configuration file (file properties with key pairs / value) in the application and read the same to the startup application. Since there is not Properties.load () as in J2SE I set out to write my own implementation to achieve the same.
After the turorial in this link , I wrote the following code:
private void loadConf() { try { InputStream confStream = getClass().getResourceAsStream("/conf/file.txt"); InputStreamReader isr = new InputStreamReader(confStream); char c; while ((c = (char)isr.read()) != -1) { System.out.print(c); } System.out.println("Out of try"); } catch(Exception ex) { System.out.println("Error: " + ex.toString()); } System.out.println("About to leave"); }
However when I call this method the moment does not seem to break on read()! = - 1 condition. That is to say. Execution does not reach to try a print statement. All the content in the file is out, but the loop's break. I placed a # at the end of the file to check for read()! = # and that works very well. Looking for - 1 the right way to check the flow of end of file? Am I missing something very basic?
Thanks for any help.
strange.
I use a similar code for reading:
InputStream stream = oClassLoader.getResourceAsStream (url);
,,
oReader = new InputStreamReader (stream);
..
StringBuffer strBuff = new StringBuffer();
..
Ihab int = - 1;
do
{
Ihab = oReader.read ();
If (ihab! = - 1).
strBuff.append (ihab (char));
}
While (ihab! = - 1);
works very well
Tags: BlackBerry Developers
Similar Questions
-
Reading for sax parser input stream
Hi all
I'm coding using JDE 4.6 on BB 9000 with Eclipse Simulator.
I received several thrusts in my BlackBerry app in succession. Can be anywhere from 5 to 17 distinct growth of xml data. I use a sax parser to go through the XML and get into my objects.
First of all, I need to read the first xml node to see what type of data it is. Once I know I then called the appropriate sax xml parser. The problem is that if I'm reading the input stream for the first node in the xml, the input stream gets consumed (i.e. missing). I now know what it contained, but now I can't parse through the xml data that I don't have an input stream to the sax parser.
What I've done so far has been to make a copy of the input stream (I made my own copy of the input stream class. So I then 2 input streams. The first one I use to see what is in the first xml node. Once I know I use the sax parser to analyze if the second input stream. It has been working great until now.
Problems appeared now. Usually, I make a copy of the first input stream (push) receive very well, but no matter what input streams received after that who could not get copied correctly through my copy of the input stream class. It gets stuck on this line.
_copy.write(data, 0, chunk);
Questions
(1) is there a way to see what is in the first node of the input xml stream without consuming?
(2) made a copy of the input stream a good idea?
(3) any suggestions?
Here's my copy of the input stream class
public class CopyInputStream { private InputStream _is; private NoCopyByteArrayOutputStream _copy; public CopyInputStream(InputStream is) { _is = is; try { copy(); } catch(IOException ex) { System.out.println("IOException in CopyInputStream"); System.out.println(ex.toString()); // do nothing } } private int copy() throws IOException { _copy = new NoCopyByteArrayOutputStream(); int read = 0; int chunk = 0; byte[] data = new byte[256]; while(-1 != (chunk = _is.read(data))) { read += data.length; System.out.println("chunk = " + chunk); System.out.println("read = " + read); _copy.write(data, 0, chunk); <----------- Seems to stall here every once in a while. // _copy.flush(); } return read; } public InputStream getCopy() { return (InputStream)new ByteArrayInputStream(_copy.toByteArray()); } }
You don't have to pass the input stream. As you note, a Manager do not have (or need) access to it. The parser calls your handler to process the events 'sax', as the stream is processed. The idea is to have your top-level manager only directly manage events until it determines the type of data in the message. (From what you describe, it probably occurs for the root element startElement event of the document.) When the first level manager determines this, he creates a delegated manager of correct type and stores it in a member variable. After that, as the parser continues to send events to the next level manager, it simply passes these events on the delegated manager.
Once the analysis is complete, the results of the analysis would have distributed between the top-level manager and the delegated manager that he created.
Assume that your element the document root is 'success' or 'failure', where the two types of documents require very different treatment. The basic idea would be something like this:
public class TopLevelHandler extends DefaultHandler { public DefaultHandler delegate; public startElement(String uri, String localName, String qName, Attributes attributes) { if (delegate != null) { delegate.startElement(uri, localName, qName, attributes); else if ("success".equals(qName)) { delegate = new SuccessHandler(); } else if ("failure".equals(qName)) { delegate = new FailureHandler(); } } public endElement(String uri, String localName, String qName) { if (delegate != null) { delegate.endElement(uri, localName, qName); } // else event ignored } // etc. }
-
How to convert string input streams
Can someone tell me how to convert string input streams...
There are multiple ways. I will list down few of them.
With the help of the old solution and standard java.
public
static
String fromStream(InputStream in)
throws
IOException
{
BufferedReader reader =
new
BufferedReader(
new
InputStreamReader(in));
StringBuilder out =
new
StringBuilder();
String line;
while
((line = reader.readLine()) !=
null
) {
out.append(line);
}
return
out.toString();
}
return
sb.toString();
If you use Google-Collections/guava-
InputStream stream = ...
String content = CharStreams.toString(
new
InputStreamReader(stream, Charsets.UTF_8));
Closeables.closeQuietly(stream);
If you use the common Apache library... then it is worthwhile.
StringWriter writer =
new
StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
Quick way but only work during deserialization.
String result = (String)
new
ObjectInputStream( inputStream ).readObject();
Note: ObjectInputStream is on deserialization and the flow of data must respect the Protocol of serialization to work, which may not always true in all cases.
Ultimately, the most effective solution and only in two lines using java class Scanner.
Tricky is to remember the \A regex that matches the beginning of the entry. It actually indicates Scanner to mark all of the flow, from start to beginning next (illogical).
public
static
String convertToString(InputStream in) {
java.util.Scanner s =
new
java.util.Scanner(in).useDelimiter(
"\\A"
);
return
s.hasNext() ? s.next() :
""
;
}
-
my kids are always downloading music and other things on the internet and some without reason, I lost my sound that I get an error that there is no audio device found... or being used? This was the last message according to test of microspft race driver and then tried to play something of my documents... Unable to read the audio stream: no audio hardware is available, or the hardware is not responding. Can you help? Bill
(1) try reinstalling the audio drivers from the drivers disk that shouldcame with your PC.(2) try to do a restore to the point where the problem wasn't there:Start > programs > Accessories > system tools > system restore(3) download and install the latest driver from the manufacturer's website.Best regards
Singapore Web hosting -
Element "FileChooser" something is wrong with the path of input stream cannot be null
Hello
IM test 'FileChooser' element for the moment.
That's what I got:
How to get:FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.png"); fileChooser.getExtensionFilters().add(extFilter); file = fileChooser.showOpenDialog(null); iv.setImage(new javafx.scene.image.Image(getClass().getResourceAsStream(file.getPath())));
file.getAbsolutPath () does not work either, I thought that was the reason.java.lang.NullPointerException: Input stream must not be null
what I'm doing wrong here?
works very well.p.png = picture in the filechooser package. iv.setImage(new javafx.scene.image.Image(getClass().getResourceAsStream(p.png)));
Thanks for the help.
IM using windows.The file picker chooses a file anywhere on the file system operating system.
Class resources are usually not files for JavaFX applications as javafx applications are usually packaged as jars.When you use getClass () .getResourceAsStream (someLocation), you specify to use the protocol used by the class loader of the class, who, in a jar, packed JavaFX application will be a protocol of pot, but you do not provide a location Protocol valid at your call jar, so that the system can not find the resource you ask to find. You cannot use an element "FileChooser" choose files in a jar.
Instead, you must use something like the following using the Protocol file to access the file selected in the OS file system by the file picker:
iv.setImage(new javafx.scene.image.Image(file.toURI().toURL().toExternalForm()));
Here is an example png image viewer application where you can see it in action: https://gist.github.com/jewelsea/5165446
-
Scheduled backups, TSM match times will fail with the following error
' RMAN-00565: cannot read the input file.
BIA-01506: fflush() failed (OSD return value = 5). »
And flooding the natural logarithm of exit with the following error
' RMAN-00558: error occurred during parsing of order entry.
RMAN-01006: error scored during the analysis
' RMAN-00600: internal error, arguments [2012] [] [] [] [] "that leads to the FS is filled up to 100%.
But backups are run successfully if start us it manually. Can someone help me with thisYou will need to set echo on inside your execution block.
#!/bin/ksh .
.env rman target=/ nocatalog log="${BKP_LOGS}/tsm_${ORACLE_SID}_ARCH_$(date '+%y%m%d@%H%M%S').log" run { set echo on allocate channel t1 type 'SBT_TAPE' parms 'ENV=(TDPO_OPTFILE=/usr/tivoli/tsm/client/oracle/bin64/tdpo_${ORACLE_SID}.opt)'; backup archivelog all delete input; release channel t1; set echo off } -
Hi all
I use NIDAQmx 9.0.2 (C++, Windows XP) and I need to read data from several channels of an NI 9229 USB card. My request will receive an another application requests to read samples, as in the following example:
-1: my application is requested to read samples from "Dev/ai0.
-(1 is not yet completed at this stage) 2: my application is requested to read samples from "Dev/ai2.
-(1 et 2 ne sont pas terminées à ce stade) 3: my application is requested to read samples from "Dev/ai4.
-my application is requested at the end 2
1 and 3 are still running at this stage
etc...I thought I had a thread for each read request, but I understand this post on the forum, this isn't an option (?).
In addition, the suggestion (in the same post) to use a single task for the acquisition of data from both channels is not sustainable for me, because I do not know beforehand what channels, I'll be forced to read from and at what time.
Is this kind of behavior can be implemented in NIDAQmx at all? If so, someone has an idea how this could be done?
Thank you in advance for any input!Hello
The NI USB-9229 has only a single timing engine. Therefore, you can read each channel independently. One possible way to implement would be to read the four channels at all times. Then, when your other application request samples from a given channel, use software to separate the samples you want for this channel.
Kind regards
-
How to read the input data at intervals of 15 Minutes for 14 days
Hello Abul,
You can use reading worksheet function to read the data from the worksheet. You may need to start by importing current data to a CSV file before using this feature as LabVIEW cannot read Excel files.
From there, you can send the picture in a chart in waveform on the front panel.
To summarize each variable, you must select a column with the function array index and use the function of elements of array add to get the sum.
-
Shared blackBerry Smartphones input stream is broken on OS 5.0?
Hello
I have developed a player for using JDE 4.5 that has always worked for me.
Now, I wanted to test the same OS 5.0, but SharedInputStream seems to be broken on OS 5.0. It always returns-1 for the second reading on the http call. Can someone help me with this. This blocks my release that reading does not at all.
Thank you
Sona
If it is set at 6.0. Should use the circular buffer for 5.0 phones
-
How to read the video stream directly with Flex?
I'm trying to get Flex Builder 3 to play a video stream with Flash Media live
Server and Flash Media Live Encoder.I am able to stream pre-recrorded (VSD) files in flex FLV go the Flash media server.
I am able to stream live using Flash/FMS/Flas Live Media Encoder, but do not
with Flex.This stream of video on demand flvs, but not live streams prerecorded code:
If I change the source to 'rtmp://localhost/live/livesream.flv, I get nothing.
What I am doing wrong?
<? XML version = "1.0"? >
<!--controls\videodisplay\VideoDisplayFMS.mxml-->
"< mx:Application xmlns:mx ="http://www.adobe.com/2006/mxml">".< mx:HBox >
< mx:Label text = "RTMP FMS 2.0" / >
< mx:VideoDisplay
autoBandWidthDetection = "false".
source = "rtmp://localhost/vod/Legend.flv" / >
< / mx:HBox >
< / mx:Application >Oh and sorry for the double post. I didn't know there was a separate instance of the FMS.
I use the video display component, but there is no "on-line" property. Try what setting to true. If it still does not work, try to remove the name of the stream of the .flv extension.
-
I need the code of aid or for example. I have some CF MX 7.0.1 and I was able to send XML requests to sellers and to accept and deal with their responses. Now, I would do the same for my clients.
I have problems with the implementation of a listener to transfer the stream to a structure that I can handle. Any help would be great.
Thank you.
See the attached code to begin.
-
Difficulty playing the big audio files/streams.
Hi all
I have an app that plays media (audio/x-wav). The application is configured to listen to and read the audio data from a web service. After that audio plays for the first time, the sound will be saved on the device. Whenever the audio selected is played later, he can read the stored file.
Everything works fine, except when it comes to playing audio files. When the Player tries to read the audio data from a big-InputStream, the application will take a few minutes to retrieve the stream and then the player will hit a State of 'ERROR', due to:
"Media cannot start while another media is active"
. At this point, I did not open another medium, however. Then when I try to play the audio again (this time this time locally from a stored FAT deposited (~ 5 MB), the application appears to hang - but it not to plant, it becomes just does more for about ten minutes.) After ten minutes, the player will reach the State of "ERROR" an error of:
"Unload failed: Timed out waiting for UD|LD"
Has anyone else had similar symptoms when you try to play larger audio files? What could be going on here? Here is my code:
Reading an input stream:
try { Player player = Manager.createPlayer(responseData,"audio/x-wav"); player.addPlayerListener(new PlayerManager()); player.realize(); player.prefetch(); player.start(); } catch (IOException e) { System.out.println("ERROR: " + e.getClass() + ": "+ e.getMessage()); } catch (MediaException e) { System.out.println("ERROR: " + e.getClass() + ": "+ e.getMessage()); }
Reading a file:
try { Player player = Manager.createPlayer("file:///SDCard/Blackberry/music/" + file); player.addPlayerListener(playerListener); player.realize(); player.prefetch(); player.start(); } catch (IOException e) { System.out.println("ERROR: " + e.getClass() + ": "+ e.getMessage()); } catch (MediaException e) { System.out.println("ERROR: " + e.getClass() + ": "+ e.getMessage()); }
PlayerListener:
public class PlayerManager implements PlayerListener { public void playerUpdate(Player player, String event, Object eventData) { System.out.println("PLAYER EVENT: " + event); if (event == PlayerListener.ERROR) { Notify.alert(Constants.PLAYER_ERROR); } else if (event == PlayerListener.END_OF_MEDIA) { try { player.stop(); player.close(); player = null; } catch (MediaException e) { System.out.println("ERROR: " + e.getClass() + ": " + e.getMessage()); } } } }
Yet once again, I'd appreciate any help!
I solved this problem for my application. Check it out at:
It will be useful.
Scott
-
How can I read from the InputStream when I use StreamConnectionNotifier
I want to make a program that will listen on port 100 and exchange with PC message.
And the program uses wifi to connect with the PC.
I have StreamConnectionNotifier choice and I can receive request for socket of PC, but when I open imputStream, Exception throw.
My code:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;Import javax.microedition.io.Connector;
Import javax.microedition.io.StreamConnection;
Import javax.microedition.io.StreamConnectionNotifier;SerializableAttribute public class ServerThread extends Thread {}
constants
private public static final String URL = ""http://:100;interface=wifi;deviceside=false "; "
fields
private StreamConnectionNotifier _notify;
private InputStream _in;
private OutputStream _out;
private StreamConnection stream = null;
private HelloWorld _app;
Private boolean isStop = false;
public ServerThread() {}
}
{} public void setApp (HelloWorld app)
_APP = app;
}
public void run() {}
try {}
{while(!isStop)}
{Synchronized (this)}
_notify = Connector.open (URL) (StreamConnectionNotifier);
}
Stream = _notify.acceptAndOpen ();
_in = stream.openDataInputStream (); //<-- i="" think="" this="" line throw="" excepiton,="" excepiotn="" 's="" message="" is:request line="" is="">-->
_out = stream.openDataOutputStream ();
extract the data from the input stream
StringBuffer sb = new StringBuffer();
Reference int = - 1;
{While (-1! = (reference = {_in.read ()))}
Reference of the SB. Append ((Char));
}
_APP.updateText (SB. ToString());
StringBuffer res = new StringBuffer();
Res. Append ("HTTP/1.0 200 OK \r\n");
Res. Append ("Content-type: text/html \r\n");
Res. Append ("Content-Length: 1 \r\n");
Res. Append ("1");
_out. Write (res. ToString(). GetBytes());
_in. Close();
_out. Close();
_notify. Close();
}
} catch (IOException e) {}
probably the stream has been closed.
System.Err.println (try ());
_APP.updateText (try ());
} {Finally
try {}
If (stream! = null) {}
Stream.Close ();
}
} catch (Exception ex) {}
}
try {}
If (_notify! = null) {}
_notify. Close();
}
} catch (Exception ex) {}
}
}
}
{} public void stop()
isStop = true;
try {}
If (stream! = null) {}
Stream.Close ();
}
} catch (Exception ex) {}
}
try {}
If (_notify! = null) {}
_notify. Close();
}
} catch (Exception ex) {}
}
}}
When I use IE application this port the program can block reading of inputStream.
What's wrong? Please help me.
What could happen is the following (Please check if this is the case however). Your code side device receives an incoming connection, but is then stuck on waiting for InputStream.read return anything. This translates your code aside PC it also blocks its BufferedReader.readLine, because the device-side code is not send anything (yet). So, you have a classic network impasse. If it is exactly what is happening, then you can try to fix the problem in several ways.
1. change the code aside device to read byte-by-byte (int InputStream.read () instead of void InputStream.read (byte [],...)). It might help because on a few BlackBerrys the TCP stack returns the data received so that the stream is closed by a peer until you start viewing byte-by-byte.
AND/OR
2. change the PC-side code to close the output stream before reading the input stream (that's how works HTTP/1.0, for example). It might help because on a few BlackBerrys the TCP stack does not return data received until the stream is closed by a peer.
-
Hi guys, I'm a ConnectionClosedException: stream is closed when reading an input stream taken after a response received from the side server.
This problem is on a single device of BB 9860.
Here is the code:
DeviceMiniPcProtocol response = null;
OutputStream outputStream = null;
InputStream inputStream = null;SocketConnection customer = null;
try {}
client = (SocketConnection) Connector.open)
"socket://10.1.1.1:8989; interface = wifi. "
Connector.READ_WRITE);
} catch (Exception e) {}
listener.onErrorReceived (message.getOperation (), "Error connecting to Server");
}If (customer! = null) {}
try {}
outputStream = client.openOutputStream ();outputStream.write (message.getCommandParsed () .getBytes ());
outputStream.flush ();
outputStream.close ();Byte [] responseDataLength = new ubyte [5];
Byte [] responseData;
int bytesToRead;
String context;inputStream = client.openInputStream ();
If (inputStream.read (responseDataLength, 0,))
(responseDataLength.length) > 0) {}
bytesToRead = Integer.parseInt (new String)
responseDataLength));
responseData = new ubyte [bytesToRead];If (inputStream.read (responseData, 0, responseData.length) > 0) {}
Context = new String (responseData);
Context = CryptoUtils.decrypt (context);response = new DeviceMiniPcProtocol();
response.handleMessage (context);
}
}inputStream.close ();
customer. Close();listener.onResponseReceived (response);
} catch (InterruptedIOException e) {}
listener.onErrorReceived (message.getOperation (),
"Timeout received');
} catch (Exception e) {}
listener.onErrorReceived (message.getOperation (), "Error sending message");
}
}After this line: If (inputStream.read (responseDataLength, 0, responseDataLength.length) > 0) I get the exception and there is no available bytes to read, but actually, the server returns data to this customer.
I appreciate the help that you could give me.
Kind regards
Jesus
I found the problem.
I changed to close the stream and connection in a finally block.
Thanks anyway!
-
How to publish the source code
How best to publish the source code?
I need an alternative to fall back on. How I would go to this topic if I had to use HTML.
My chance to validation code has deteriorated over time. I did it via:
I take the plain.
Yesterday, when I tried to insert the Bash source code. I had a lot of white lines. I think that leading # confused CSA.
#!/bin/bash # so anyway, output from the echo statement is sent to the terminal. The operands < and > # allows you to change where it is going. # default redirection # 0 stdin -- standard input # 1 stdout -- standard output, non-error output # 2 stderr -- standard output for error messages. # had not used the exec statement before, the concept of the exec was # readily apparent to me. # of course, I ripped this off. Turns out you want to preserve where input stream 0 is # coming from. The hack moves input stream 0 to input stream 6. Pick any number # that is allowed. # save standard input in file descriptor 6 exec 6<&0 # now we say where we want input stream 0 to come from. # bash has an unknown to me number of commands that read from input stream 0 # via redirection we can change were stream 0 is coming from. # redirect standard input to be from the passed file exec 0<${1} count=0 while read lineIn do { # bash syntax is bizarre. # The (( )) says it's a math expression (( count++ )) echo "${count}: ${lineIn}" } done # put the input streams back to where they were before. # Nice, but when the script quits they will all be put back to where they were. # Of course, I copied this stuff. Syntax isn't the obvious. # close input. May not need. My innovation. Seems nice. exec 0<&- # restore file descriptor 0 should be standard in exec 0<&6 # close file descriptor 6 for reuse. exec 6<&- echo echo "Total lines were ${count}"
Do you get the extra lines before applying syntax highlighting? You can simply change the Courier New font.
#! / bin/bash
# Anyway, Exit statement echo is sent to the Terminal. The operands< and="">
# allows you to change its future.
default redirection #.
# 0, stdin - standard input
# 1, stdout - output standard output without error
# 2, stderr - standard output for error messages.
# did not use the exec statement before, the concept of the exec has been
# obvious to me.
# good course, I snatched it. Turns out you want to keep where the input stream 0 is
# coming. The cut moving the input stream to the stream input 6 0. Choose any number
# who is allowed.
# Save the standard entry in the file descriptor 6
exec 6<>
# now say us where we want to enter flow 0 to come from.
bash # a a stranger to me the number of commands that read from the input stream 0
# via redirection, we can change were stream 0 comes.
# redirect the standard input from the file passed
exec 0<>
Count = 0
while reading lineIn
{}
bash # is weird syntax.
# (()) Is a mathematical expression
((count ++))
echo "${number}: ${lineIn}.
}
fact
# put the input stream to where they were before.
# Nice, but when the script closes they will all put back to where they were.
# Of course, I copied this kind of things. The syntax is not obvious.
# entry closes. May not need. My innovation. Seems nice.
exec 0<>
Restore file descriptor # 0 should be standard in
exec 0<>
# close the file descriptor 6 for reuse.
exec 6<>
ECHO
ECHO "the Total of the lines were ${number}.
TT2
Maybe you are looking for
-
How can I change the browser title suffix "-Mozilla Firefox"? If I want to change it.
-
Firefox 7.0 is not supported by my Blackboard Vista required at school
How can I downgrade to an earlier version of Firefox? I just upgraded to 7.0, and now Blackboard (compulsory school programme) said that the version of Firefox that I use is not supported.
-
This is a picture where my current monitor is connected to my computer: http://i49.Tinypic.com/2a98fht.jpg I guess the extra space near the monitor cord is where you would plug in another monitor/TV or all that but I don't know much about computers s
-
Impossible to multi monitor in windows xp
I got a PC by a family member and wish to multi monitor. Indicates the PC have windows XP. When I access the control/display panel etc. There is no available in multi monitor option. I've never experienced this before. Can someone give me advice plea
-
Unable to connect to live in age of empires online
Unable to connect to live you may be using a native wlid in a region that is not supported by direct but has functioned well yesterday