Multi-line reading from applet?

I just began using a technique to get a single value
from the web server to my applet via CGI-BIN.
Please see relevant code below.
With this technique -I was given a chunk of code, I don't
even understand its behavior completely- I can retrieve
one value from the server. Now I would like to retrieve
multi-line data, such as that coming from a SQL statement which
will be used to populate my applet's menus.
So, how should I retrieve this cursor-like, or stream data?
I suppose I need to put the "s = d.readLine()" statement inside
a loop, but what loop variable shoould I use??
TIA,
-Ramon F. Herrera
URL url;
URLConnection urlConn = null;
DataOutputStream dos;
DataInputStream dis;
InputStream is;
url = prepareServerCommand(Id, true);
try {
urlConn = url.openConnection();
} catch (IOException ex) {
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String s = null;
try {
dos = new DataOutputStream(urlConn.getOutputStream());
String message = "NEW_ITEM=1";
dos.writeBytes(message);
dos.flush();
dos.close();
is = url.openStream();
BufferedReader d = new BufferedReader(new InputStreamReader(is));
s = d.readLine(); // <-- THIS NEEDS TO BE INSIDE A LOOP!!
d.close();
} catch (IOException ex1) {
jButton1.setText("Number of Items:");
jTextField1.setText(s);
done = 1;
return (done);

Here's a way:
String $URL = "http://server.com/cgi-bin/a.cgi?whatever=1";
try{
URL url = new URL($URL);
BufferedReader in =
new BufferedReader(new InputStreamReader(url.openStream()));
String $nextline, $returned = "";
while(($nextline = in.readLine()) != null){
$returned += $nextline + '\n';
if($returned.indexOf("END OF DATA") > -1) break;
in.close();
}catch(Exception e){System.out.println("ERROR: " + e);}
System.out.println($returned);
Note the line containing "END OF DATA". The reason I did that was that the connection was just getting stuck in that loop for too long. By using something to mark the end of the data, I was able to break out of the loop sooner. Maybe there's a better way but I don't know it.

Similar Messages

  • Convert a line read from text file into string

    how to convert a line from text file into string?
    i know how to convert to numbers,
    private int  parseLine1(String line) {
              StringTokenizer tokenizer = new StringTokenizer(line);
                  value1 = Integer.valueOf(tokenizer.nextToken()).intValue();
                  value2 = Integer.valueOf(tokenizer.nextToken()).intValue();
                 return value1;
                     }but what about charactrs?

    ok, here is my problem, i have a file with a bunch of Xs in it but position function doesn't return a correct value, what's going wrong?
    private int positioni(){
           int i=0;
           int j=0;
           int b=0;
           String line="";
            while(line!= null){
                for(int a=0; a<line.length(); a++){
                    if(line.charAt(a)=='X'){
                        i=a;}
                b++;
                j=b;
                t=line.length();
                line=read(gridFileN);
           return i;
    private String read(String ggridFileN){
             TextStreamReader ggridFile = new TextStreamReader(ggridFileN);
             return ggridFile.readLine();

  • Copy multi line oftext from enhanced to plain retreives HTML

    Hi,
    I have two multi line columns, one in enhanced mode and one plain text. when i use quick view to copy all the values from enhanced to plain, it paste all the html tags alongside the text.
    Any thoughts how to eliminate that and copy only the text?
    Thanks a lot in advance

    Hi,
    You can edit list items in DataSheet view and copy items.
    Thanks,
    Vivek
    Please vote or mark your question answered, if my reply helps you

  • Multi lines read in ALV using FM

    Hi,
    I have an ALV report, in that one fld is in edit mode the value can change for multi lines , when I click on a button the  changed values need to store some where.
    if it is '0' delete that record other wise refresh ALV. I have used FM in my report .can you help me?
    and is it possible to do validations like retain the value if it is wrong entry.
    Please help me

    HI,
    Check similar thread.Especially first 2 answers.
    Re: How to Refresh an ALV-grid created with FM REUSE_ALV_LIST_DISPLAY

  • Feature request : import of multi-line notes in CSV or tab-delimited file

    This is a feature request to the AddressBook development team:
    Following a question posted here and asked to support (thanks to Barry and Julia from ADC), it turns out that AddressBook is not ready yet to import multi-line notes from a CSV or tab-delimited file.
    I would like to kindly suggest the AddressBook development team to update the import methods for such flat files to parse the text of what is assigned to the Notes field, and convert documented escape sequences to their pre-determined corresponding special character.
    I would think that the following would be pretty easy to implement, and easy for the targeted audience (enthousiasts power-users and up) to remember:
    "\n " : mark a new line (same as ^p in Word)
    "\t " : replace by a tab
    I would keep the trailing space to avoid problems with DOS-type file path problems.
    and of course...
    "\\n " and "\\t " for whoever would want to import notes about \n and \t
    For example, in a Notes column, the text:
    "Escape sequence \\n :\n move the text to a new line\n \n while escape sequence \\t :\t move the text to the next horizontal tab"
    would give the following (just consider text between <Note> marks):
    <Note>
    Escape sequence \n:
    move the text to a new line
    while escape sequence \t: move the text to the next horizontal tab
    </Note>
    Thanks for reading...
    Frédéric Denis

    The developers do not necessarily read these USER discussion pages. If you want to make suggestions and know they will be read (which is at least a step towards implementation) use the OS X feedback page.
    AK

  • Can someone test a prog for me, and help reading from an exty file

    Okay, I have a program to calculate the Pearson product-moment correlation coefficient ( http://en.wikipedia.org/wiki/Pearson_correlation_coefficient ) from an external file that I've just written for an assignment on Monday.
    I can't actually run it because I can't find a machine with Java on that works, though I can compile it. Why is a long story, but University Admin are going to feel my wrath.
    I would like two things.
    1) would someone be kind enough to try to run it and test it in anyway and report any bugs or inadequacies back to me. (you will need to create a text file called data.dat with some numbers in, e.g.
    14.234 54.4534
    376.56 432.2332
    23432. 23234.23
    2) How can I can the computer to ask the user to enter either a) the name of the file from system.in or b) from a popup dialogue box with a browse feature (or is that incompatible with some OSs?).
    The file follows:
    // Import packages
         import java.io.*; // Import all the Java input/output packages
         import java.util.StringTokenizer; // Import a utility package
    class Pearsontwo
    public static void main (String[] args)
         /* Define variables.
              (double any number with decimal point.
              ints take integer value) */
              double     sumx, sumy,               // sum of x and sum of y
                        sumxx, sumyy,          // sum of x squared and y squared
                        sumxy;                    // sum of products of x and y
              int n;                              // n is number of lines
         // Set name of file to be read
              String fileName = data.dat; // define the name of the file
         //     (Enhancement: use user input. This requires the use of System.in which is a bit complicated.
              //System.out.print("Please type the name of the file you wish to run the analysis on:");
              //fileName = TextIO.getInt();
         // Set things for reading external file
    BufferedReader br;     // Will be used to read the file
    String line;          // Will be used to hold a line read from the file
    StringTokenizer st; // Will be used to break a line into separate words
              String firstWord, secondWord;     // File will be read as string type
    double firstNumber, secondNumber;     // that need to be converted into numbers.
    try // if an error occurs, go to the "catch" block below
    // Create a buffered file reader for the file
         br = new BufferedReader (new FileReader(fileName));
    // Continue to read lines whilst there is one or more left to read
                        while (br.ready())
                        {   line= br.readLine();               // Read one line of the file
                             st = new StringTokenizer(line);     // Prepare to split the line into "words"
                             // Get the first two words (invalid --> error --> catch)
                                  firstWord = st.nextToken();
                                  secondWord = st.nextToken();
                             // Turn words into numbers (invalid --> error --> catch)
                                  firstNumber = Double.parseDouble(firstWord);
                                  secondNumber = Double.parseDouble(secondWord);
                             // Add the numbers to the previously stored numbers
                                  sumx = sumx + firstNumber;
                                  sumy = sumy + secondNumber;
                                  sumxx = sumxx + (firstNumber * firstNumber);
                                  sumyy = sumyy + (secondNumber * secondNumber);
                                  n = n++; add one to the value of n.
    // Close the file
    br.close();
    // Handle any error in opening the file
                   catch (Exception e)
                   {   System.err.println("File input error.\nPlease amend the file " + fileName);
              //     Calcuate r in stages, variance and covariance first.
                   double variancex = (sumx2 - (sumx * sumx / n)) / (n - 1);     // calculates the variance of x ...
                   double variancey = (sumx2 - (sumx * sumx / n)) / (n - 1);     // ... and y
                   double covariance = (sumx * sumy - sumx * sumy / n ) / (n - 1);     // and the covariance of x and y
                   double r = covariance / Math.sqrt(variancex * variancey);     // and the Pearson r value
                   // Printout
                   System.out.print("The Pearson product-moment correlation for these data is:" );
                   System.out.println ( r );
                   // Also print to file ?
    Cheers,
    Duncan.
    (Note: this is my own work by Duncan Harris at Cariff University, so I'm not plaigerising anyone other than myself if I post it here and it subsequently gets found by one of the course organisers who have given permission for this sort of thing anyway!)

    "I can't actually run it because I can't find a machine with Java on that works, though I can compile it. Why is a long story, but University Admin are going to feel my wrath."
    I'm sure they're worried.
    I don't understand this. You can compile, but not run? This makes no sense at all.
    Why can't you simply download the JDK from Sun and install it on a machine? You could both compile and run then.
    You don't need a pop-up dialog box to get an input file name from a user. The command prompt is quite sufficient.

  • Reading from the Applet's JAR file.

    Is it possible to read a file stored in the jar file that the (unsigned) applet is being executed in? I have a line that goes like (in is just an InputStream):
    in = getClass().getResource( "/exercise.xml" ).openStream();
    and then, in another class, i do (bulider is an instance of javax.xml.parsers.DocumentBuilder, created from the DocumentBuilderFactory class):
    doc = builder.parse( in );
    but this always results in a security exception (works fine from the applet viewer). I tried specifying the full path to the .jar file as the codebase, but got the same results. I have not tested this from an actual web server, i am only opening the .html file directly in IE.
    Due to the nature of the application, it is not possible to host the file seperately on a webserver.
    It seems to me that there is no reason an applet shouldnt be allowed to load a file from the .jar it is executing in, could this simply be a problem of the file being local, and thus linked to from a file:// tag?
    Thanks for any help.
    Thomas Stephens

    Hi Guys
    I have figured out this problem. It's got to do with classloader.
    Applet uses a separate classloader. So using the static getSystemResource(),
    we never get contents from applet jar files. The following will work nicely.
    It is noted that you must loacate the applet classloader as in the first line
    and use the non-static method getResource();
    ObjectInJar obj = new ObjectInJar(); // create an object with a class in the jar file.
    ClassLoader cl = obj.getClass().getClassLoader();
    InputStream stream = cl.getResource("your_filepath_in_jar").openStream();
    Cheers.

  • Reading a semi column delimited multi line Flat file on KM repository

    Hi,
    I have a requirement in our project to read a multi line, semi column delimited flat from kept on the Knowledge Management repository and display the contents in the Portal.
    I had tried couple of options and was unable to read the file. I am not sure which are the correct APIs I should be using.
    Can any one of the experts could guide me with the sample code, that will be great!
    Your early response is highly appreciated.
    Regards
    Venkat

    here you go.
    //******* Read file from KM
    String repository_km;
    String FileURL;
    repository_km="/documents/data/data.txt";     
      try
    //Getting the user......
      IWDClientUser wdClientUser = WDClientUser.getCurrentUser();
      IUser sapUser = wdClientUser.getSAPUser();
      com.sapportals.portal.security.usermanagement.IUser ep5User =
      WPUMFactory.getUserFactory().getEP5User(sapUser);
    //Getting the Resource.........
      IResourceContext resourseContext = new ResourceContext(ep5User);
      IResourceFactory resourseFactory = ResourceFactory.getInstance();
    //path to the KM Folder ("/documents/data/data.txt")
      RID rid= RID.getRID(repository_km);
      com.sapportals.wcm.repository.IResource resource =
      resourseFactory.getResource(rid, resourseContext);
    if (resource != null)
         String text = "";
         BufferedReader in = new BufferedReader(new InputStreamReader(resource.getContent().getInputStream()));
         int count=0;
         while ((text = in.readLine()) != null)
         strText[count] =text;
         count++;
    catch (RuntimeException e2) {
    wdComponentAPI.getMessageManager().reportException("Error in reading file from KM : "+e2.getMessage(),true);
    //                  TODO Auto-generated catch block

  • Saving an array of multi-line text cells in a format that can be read in later

    I can create an array of multi-line text entries that my program can then pick cells and compile them into a list of text.
    I would like to be able to Save the array as a file, then change my program to read in the file.
    If I use the Save Spreadsheet file vi, the data is corrupted by the carriage returns within the cells and the data read in is messed up.
    Can someone recommend a way to save the array that preserves the carriage returns?

    As far as I know, this cannot be done automatically with the basic VIs from the palletes.  I would convert the [LF] into another group of characters (likely "\n") and then save the text array to a CSV file.  Don't forget to escape any good "\" string with an extra "\.  Regular expressions would work really well:
    Just make sure you parse your entire array of strings with this.
    Olivier
    Attachments:
    SaveToCSV_WithMultiLine.vi ‏9 KB

  • Read from a text file line by line

    Hi,
    I am new to Labview and I am trying to output a text file line by line. For example if my text file is
    START
    SETRPM 1000
    WAIT 10s
    RAMP RPM linear,1000,2000,2 MAF linear,5,7,2
    WAIT 5s
    RAMP RPM sine,2000,1500,3 MAF sine,7,3,3
    END
    I want it to output
    START
    SETRPM 1000
    SETMAF 5 ...and so on
    I tried modifying this code provided by Altenbach but it is still not working as I want it to. Can anyone direct me toward how I can fix this?
    Thank you!
     

    Your program does exactly what you asked it to do.  In particular, it will repeat 10 times, at one per second, reading (and storing in String) the (unchanging) data that you bring in on the Shift Register.  This data will consist of the first line of the (assumed-)multi-line file you specified.
    I suppose your question is "Why is it only showing me one line?"  This is where it really pays to "Read the Directions Carefully" (or, in this case, carefully read the Help for Read from Text File).
    Bob Schor
    P.S. -- I pointed your code at a text file of 7 lines on my PC.  When I made a few small changes (including doing away with the silly For loop that shows the same thing over and over) , I got out an array, size 7, containing the lines of text.

  • "read from measurement file" reads only first line of data

    Hello,
    I have a problem when trying to read a .lvm file through "Read from Measurements file" with the following block diagram
    Problem: it reads only the first line of data from what I can see in the probe window,.
    A part of the lvm file for reference.
    I haven't used Labview in a long long time, I'm trying to figure out what I am doing wrong.
    Thanks

    Sorry meant to attach the lvm. Here it is. (Actually I had to put it in .txt because the forum wont let me upload a lvm file)
    I unfortunately cannot share the full vi that record the data as I am not its owner/creator. I'll try to give as much info as I can with the relevant pictures attached, I hope it allows us to at least have an hint of where the problem might be.
    (this is in a while loop)
    In the stacked sequence, the other pannels are similar to the one shown here: value read fron a variable, converted to dynamic and a signal attribute is set. The "start recording" control operation is "switch when pressed".
    Here are the properties of the set signal attributes
    And here are the properties of the "write to measurement file"
    Attachments:
    NoTarget_full circle__Rx_-10-SAMPLE.txt ‏60 KB

  • Code to read local notepad.txt from applet

    Hi.
    Further to my (unanswered) queries about reading a notepad.txt file from the local directory i.e. the same directory from which the html and applet were launched, the following code is supposed to be able to read the local file. It failed to do so both in Netscape 7.1 and in IE5
    I've also received conflicting advices : some says we can read local files without using a signed applet or chaning the ACL, whereas others I'll need to use signed applets and / or acl to allow the applet to read a local file.
    My research has shown that java applets are supposed to be able to read local files. Has something changed:
    public class FileAccess extends Applet
       implements ActionListener {
       Button loadButton, saveButton;
       TextField filename;
       TextArea  content;
       String browserName;
       boolean securitySupported = false;
       public void init() {
         setLayout(new FlowLayout());
         Label label =
           new Label("Simple file editor");
         add(label);
         loadButton = new Button("Load");
         saveButton = new Button("Save");
         add(loadButton);
         add(saveButton);
         loadButton.addActionListener(this);
         saveButton.addActionListener(this);
         filename = new TextField(20);
         add(filename);
         content = new TextArea(5,20);
         add(content);
         browserName = System.getProperty("java.vendor");
         if (browserName.indexOf("Netscape") > -1)
            securitySupported = true;
         setSize(200, 200);
       public void actionPerformed(ActionEvent evt)  {
         if (securitySupported) {
            if (evt.getSource() == saveButton) {      
               PrivilegeManager.enablePrivilege("UniversalFileAccess");
               try {
                  FileWriter aWriter = new FileWriter(filename.getText(), false);
                  aWriter.write(content.getText());
                  aWriter.flush();
                  aWriter.close();           
               catch(Exception e) {
                 e.printStackTrace();               
            else if (evt.getSource() == loadButton) {
               PrivilegeManager.enablePrivilege("UniversalFileAccess");
               try {
                  BufferedReader aReader  =
                     new BufferedReader
                        (new FileReader(filename.getText()));
                  content.setText(aReader.readLine());
                  aReader.close();           
               catch(Exception e) {
                 e.printStackTrace();               
          else {
            getAppletContext().showStatus("security not installed");
    }

    Hi acinhk,
    I read your note with great interest. I am trying to solve almost exactly the same problem as you are -
    Reading a .txt file in IE5 from the same directory where the html and the applet were lauched.
    Your code looks fine to me.
    My code is very similar, and again generates a security exception - as I am having the same problem you had getting around Java security.
    If you have been able to solve the problem, can you please let me know what you did.
    Any modifications to your sample code that actually made it work would be greatly appreciated.
    Also, is signing the applet to read a local file under IE5 really necessary ?
    Can the file be read from the local IE file system without signing the applet ?
    Please let me know your thoughts.
    Thanks !
    drbob

  • How to read from a file line by line

    Hi
    I am new to using LabView and was wondering how I could read data from a text file one line at a time and display this data one line at a time as well. I tried looking through the Reading from Text File . vi example but that just seems to be reading and displaying everything together.
    Thanks
    -Karan

    Hi
    My aim is to read text line by line and to then go ahead and display the last 8 reaad lines of code to give the impression of text falling down a screen. I tested the first while loop and that seemed to work fine. However, when I encounter an EOF, I would like the text already read to keep making its way down the screen and keep inputting NULL characters into the array to simulate the effect of the text falling down the screen which is why I created the second while loop. I tried to input the NULL characters using a box for ENUM constants. However, I kept getting an error saying the data types do not match. What would I need to do? For the display I plan on putting indicators next to the 8 places where the text would be stored which I have not done so far.
    I am also attaching a copy of the error.
    Thanks
    -Karan
    Attachments:
    DisplayText.vi ‏40 KB
    Error.JPG ‏89 KB
    PictureOfBlock.JPG ‏120 KB

  • I receive daily emails from the NY Times, which I read from my Ipad. Some of the emails will show all of the stories available, and some will only show a few lines in the body and the rest of the email is blank. Any ideas of what I need to do to fix this?

    I receive daily emails from the NY Times, which I read from my Ipad. Some of the emails will show all of the stories available, and some will only show a few lines in the body and the rest of the email is blank. Any ideas of what I need to do to fix this?

    Try a reset: Simultaneously hold down the Home and On buttons until the device shuts down. Ignore the off slider if it appears. Once shut down is complete, if it doesn't restart on it own, turn the device back on using the On button. In some cases it also helps to double click the Home button and close all apps from the tray before doing the reset.

  • [JS] [CS2] Change all from multi line to single line composer

    Hi
    Does anyone know how to change all paragraphs, on all pages, in all textframes, from multi line composer to single line composer...
    Thanx
    Tim

    This should work:
    app.documents[0].stories.everyItem().composer = "Adobe Single-line Composer"
    Dave

Maybe you are looking for

  • Probook 4530s drivers

    Hello, i got my laptop HP 4530s i3, it came with Linux preinstalled. I have installed windows 7 ultimate x64 and i tried to find as many drivers as possible. I couldnt find 5 drivers plz help me. laptop p/n: A1E83EA#ABV yellow signs: 1)Generic Blueto

  • Problem with Serializable JDO objects containing Hashtables

    Hi, I have a simple JDO object which contains a Hashtable and I would like to declare as Serializable. It seems though, that whenever I serialize this object, I get a NullPointerException. I've written a bare-bones test case and reproduced the except

  • Out of memory error when writing large file

    I have the piece of code below which works fine for writing small files, but when it encounters much larger files (>80M), the jvm throws an out of memory error. I believe it has something to do with the Stream classes. If I were to replace my PrintSt

  • Misleading documentation to creation VO?

    in the doc is written> Note: If you create a view object using this method, the query may be executed twice the first time you fetch data. The first query collects data type and precision information, which is used in subsequent queries to map data t

  • Compile class error

    hi guys, this is going to drive me crazy... i don't think its a classpath... here is my program: package divelog; import javax.swing.*; import java.awt.*; import java.awt.event.*; * @author Administrator public class DiveLog { private JFrame dlframe;