Buffered reader / data inputstream

I need to find out how to enter array numbers in from the keyboard
i think it might be by using buffered reader, but i dont know th exact code can
anybody help me!
Cheers

Do you need to keep array of numbers?
It's simply and not powerfull solution:
import java.io.*;
import java.util.Vector;
public class test
public static void main (String argv[])
BufferedReader theIn = new BufferedReader (new InputStreamReader (System.in));
int nValue;
int nSumma = 0;
Vector theItems = new Vector (0, 10);
while (true)
try
nValue = Integer.parseInt (theIn.readLine ());
nSumma += nValue;
theItems.addElement (new Integer (nValue));
catch (Exception e)
break;
System.out.println ("Summa: " + nSumma);
}

Similar Messages

  • Buffered reader need help

    Hello!
    I'm useless at java and am trying to complete a piece of code i just don't get!
    I'm reading in a text file and don't know how to complete the buffered reader section of it can anyone help!
    p
    the code is as follows.
    // Author:
    // Date:
    // The creation of the League class
    // saved as League.java to hold and manipulate icehockey team data
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    class League
    private static Team teams[]=new Team[6];
    League()
    String tName;
    String tNickname;
    String nPlayed;
    String nWon;
    String nLost;
    String nDrawn;
    try
    FileReader fr=new FileReader("Results.txt");
    //got the following syntax from p436
    BufferedReader br=new BufferedReader(fr);
    //confused!!!!     
    int i=0;
    while()
    // dunno if this is right!
    StringTokenizer st = new StringTokenizer(fr);
    while (st.hasMoreTokens())
    //will this work?
    tName=inputStream.sval;inputStream.nextToken();
    tNickname=inputStream.sval;inputStream.nextToken();
    nPlayed=(int)inputStream.nval;inputStream.nextToken();
    nWon=(int)inputStream.nval;inputStream.nextToken();
    nLost=(int)inputStream.nval;inputStream.nextToken();
    nDrawn=(int)inputStream.nval;inputStream.nextToken();
    //whats this bit about? new team instance to be written!
    //teams=;
    i++;
    fr.close();
    br.close();
    //catch exception thing wrote this dunno if it works or not
    catch (Exception e)
    if (e instanceof FileNotFoundException)
    system.out.println("Filename"+Results.txt+"not found")
         //     public int getSize()
                   //to be written
         //     public Team getTeam(int i)               
                   //to be written

    try somethign along these lines...
        try {
            BufferedReader in = new BufferedReader(new FileReader("infilename"));
            String str;
            while ((str = in.readLine()) != null) {
                process(str);
            in.close();
        } catch (IOException e) {
        }

  • Can not read data from URL!

    Hello,
    I want to read data from URL (http://84.100.130.82:8000/;stream.nsv). But can not do it. Because when try to call function openDataInputStream() shows this error: java.io.IOException: response does not start with HTTP it starts with: ICY. How I can fix this bug?
    HttpConnection c = null;
    InputStream is = null;
    OutputStream os = null;
    StringBuffer b = new StringBuffer();
    String           response,
    responseLitle;
    c = (HttpConnection)Connector.open(“http://84.100.130.82:8000/;stream.nsv”);
    os = c.openOutputStream();
    os.flush();
    is = c.openDataInputStream();     // ERROR CODE HERE
    int ch;
    // receive output
    while ((ch = is.read()) != -1)
    b.append((char) ch);
    response = b.toString();Regards, Ramunas

    Hi, I�m trying to do the same as above, get MP3 from a Shoutcast server.
    I got the same fault ("response does not start with HTTP it starts with: ICY") when I tried to open an HttpConnection as bellow:
    ============================================
    HttpConnection conn = (HttpConnection) Connector.open("http://64.236.34.196/stream/1074");
    Then I tried to open a socket connection as bellow:
    ======================================
    SocketConnection conn = (SocketConnection) Connector.open("socket://64.236.34.196:80");
    String get = "GET /stream/1074 HTTP/1.1";
    DataOutputStream os = conn.openDataOutputStream();
    os.writeUTF(get);
    InputStream is = conn.openInputStream();
    But then I got the following error:
    =========================
    java.lang.SecurityException: Target port denied to untrusted applications
    Could someone help me to find out what is going on?
    Thanks a lot!

  • How to pre-allocate a ByteBuffer object to read data from a Socket

    Hi,
    So far every example on ByteBuffer allocation has shown something like this
    ByteBuffer buffer=ByteBuffer.allocate(1024);
    Im stuck because i dont know how much data will arrive on the socket. Is there anyway I can find out how much data is present on a socket before allocating the ByteBuffer? And if not, what can i do to ensure that I dont lose any of the data that is present on the socket and cant be read because the buffers limit may be too small.
    Thanks,
    Parth

    Hi,
    Bytebuffer is just buffer so make it big enough to handle traffic.. How big it must be depends on your applicaiotn and trasfered data amount..
    Following code shows an example which uses byte array as buffer... Following code is 1.2.x and above compatible using byte array instead ByteBuffer..
    Vector mainbuffer = new Vector(10,1);
    byte [] tempbuffer=new byte[5000]; // 5Kb buffer
    // STKInBufStr is bufferedinputstream to read data till end of stream ..
    // readcount show amount of data readed.. which means data amount in buffer. Data is written to buffer from start point -0,- 5000 is max read aomunt.
    // once read 5000 byte then it will return to while loop and create a temporary string and add it to manibuffer and menawhile coming data is not lost.. this loop will catch all incoming dta and buffer in mainfbuffer vector Roughly speaking bigger the buffer better te performance. Remeber code will wait to read 5000 byte of data to return to while loop. 5000 only means max amount of data it can handle in every read attempt.. if just read 2 byte it will return this 2 byte to loop
    while ( (readcount=STKInBufStr.read(tempbuffer,0,5000)) !=-1)
    String tmp = new String(readbuffer).substring(0,readcount);
    manibuffer.add(tmp);
    This loop will catch all incoming data and add to mainbuffer vector..

  • Reading data from a XML file.

    Hi,
      I am new user to webdynpro and has the task of reading data from XML file.The file is created using XML form Builder and is stored at a location.But my code gives me the path instead of the content in the data.
    The code is :
    try
          IWDClientUser wdClientUser = WDClientUser.getCurrentUser();
           com.sap.security.api.IUser sapUser = wdClientUser.getSAPUser();
    // create an ep5 user from the retrieved user
           IUser ep5User = WPUMFactory.getUserFactory().getEP5User(sapUser);
           IResourceContext context = new ResourceContext(ep5User);
    /Specify the path of ur document here./
           RID pathRID = RID.getRID("/documents/70f51182-84c3-2710-ce91-8d5fbfde713d.xml");
           //RID pathRID = RID.getRID("/documents/hol.txt");
           wdContext.currentContextElement().setSetDisp(pathRID.toString());
           IResource resource = ResourceFactory.getInstance().getResource(pathRID, context);                       
           InputStream in = resource.getContent().getInputStream();
           ByteArrayOutputStream out = new ByteArrayOutputStream();
           byte[] buffer = new byte[4096];
           int bytesread = 0;
           while ((bytesread = in.read(buffer)) != -1)
               out.write(buffer, 0, bytesread);
           String myData = out.toString();
    /*myFile will containS the content of the document./
           wdContext.currentContextElement().setSetDisp(myData);
           catch (Exception e)
            // wdContext.currentContextElement().setTextdisp("IO Error:" + e.getMessage());
    text data is read from the location but XML data is not read.
    Please help me out.

    hi SriRam,
      For some reasons you are not able to change the value of attribute SetDisp ahich you gave the default value as the path using the following statement
    wdContext.currentContextElement().setSetDisp(myData);
    Remove that line.First try to open the files using creating new window instance
    IWDWindow window =
                wdComponentAPI.getWindowManager().createExternalWindow(
                      "http://<server name>:<port no>/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs"
                            + "/documents/Public Documents/...."
                            + "/"
                            +<name>,
                      "from km repository",
                      false);
          window.open();
    Then we can be sure that the error is due to reading data using input stream
    Regards
    Rohit

  • Read data from Excel file and diaplay in Webdynpro

    Hi all,
    I need some help. I have a Excel file with set of  name, phonenumbers . I want to know how to display the data using Webdynpro. Could some one help me. help is appreciated and I promise to award points for right answer.
    Thank you
    Maruti

    <b>Hi
    i can explain you to read data from Excel file
    First You have to download the jxl.jar file. You can get this file from the Below site
    </b><a href="http://www.andykhan.com/jexcelapi/download.html">jexcelapi jar</a>
    It will be in Compressed Fromat So Unzip it to get the Contents
    After Unzipping The File You will get a Folder (jexcelapi/jxl.jar)
    Now in NWDS open web dynpro explorer, Right Click Your Project, a popup menu will appear and in that click Properties
    You will get window displaying your Project Properties
    On Left Side of the window You Will Find "Java Build Path"
    Click That "Java Build Path" and you will get 4 Tabs Showing ( Source,Projects,Libraries,Order and Export)
    Click Libraries Tab
    You will find options many options buttons
    In that click the Button "Add External Jars"
    You will get Window in order to fecth the jxl.jar file from the location you had stored
    After selecting the jxl.jar i will get displayed and click ok
    Now Open Navigator
    Open Your Project
    You will find Lib folder
    Copy the jxl.jar to that lib folder
    Note : You cannot Read the Content from the excel file directly
    First You Have to copy that file to the Server,
    And from the Server you can get the file absolute path
    With the absolute path you can read the contents of the Excel file
    You have to save the Excel file as .xls Format and Not as xlsx format i will not accept that...
    You have Upload the Excel file from the Server Using the File Upload UI Element
    This Coding will extract 3 columns from the Xls File
    Coding
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import jxl.Cell;
    import jxl.Sheet;
    import jxl.Workbook;
    import com.sap.fileupload.wdp.IPrivateFileUpload_View;
    import com.sap.tc.webdynpro.services.sal.datatransport.api.IWDResource;
    public void onActionUpload_File(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionUpload_File(ServerEvent)
        IPrivateFileUpload_View.IContextElement element1 = wdContext.currentContextElement();
        IWDResource resource = element1.getFileResource();
        element1.setFileName(resource.getResourceName());
        element1.setFileExtension(resource.getResourceType().getFileExtension());
        //@@end
    public void onActionUpload_File_in_Server(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionUpload_File_in_Server(ServerEvent)
        InputStream text=null;
        int temp=0;
        try
             File file = new File(wdContext.currentContextElement().getFileResource().getResourceName().toString());
             FileOutputStream op = new FileOutputStream(file);
             if(wdContext.currentContextElement().getFileResource()!=null)
                  text=wdContext.currentContextElement().getFileResource().read(false);
                  while((temp=text.read())!=-1)
                       op.write(temp);                                      
             op.flush();
             op.close();
             path = file.getAbsolutePath();
             wdComponentAPI.getMessageManager().reportSuccess(path);
        catch(Exception e)
             e.printStackTrace();
        //@@end
    public void onActionUpload_Data_into_Table(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionUpload_Data_into_Table(ServerEvent)
        try
              Workbook wb =Workbook.getWorkbook(new File(path));
              Sheet sh = wb.getSheet(0);
              //wdComponentAPI.getMessageManager().reportSuccess("Columns = "+sh.getColumns());
              //wdComponentAPI.getMessageManager().reportSuccess("Rows = "+sh.getRows());
              int columns = sh.getColumns();
              int rows = sh.getRows();
              int i=0;
             for(int j=1;j<=rows;j++)
                       ele=wdContext.nodeTable_Data().createTable_DataElement();
                       Cell c1 = sh.getCell(i,j);
                      ele.setTab_Name(c1.getContents());
                       Cell c2 = sh.getCell(i+1,j);
                       ele.setTab_Degree(c2.getContents());
                          Cell c3 = sh.getCell(i+2,j);
                       ele.setTab_Percentage(c3.getContents());
                       wdContext.nodeTable_Data().addElement(ele);
        catch(Exception ex)
             wdComponentAPI.getMessageManager().reportSuccess(ex.toString());
        //@@end
       * The following code section can be used for any Java code that is
       * not to be visible to other controllers/views or that contains constructs
       * currently not supported directly by Web Dynpro (such as inner classes or
       * member variables etc.). </p>
       * Note: The content of this section is in no way managed/controlled
       * by the Web Dynpro Designtime or the Web Dynpro Runtime.
      //@@begin others
      String path;
      IPrivateFileUpload_View.ITable_DataElement ele;
    //@@end
    Regards
    Chandran S

  • HELP - Buffered Reader

    Below is a portion of my program, its a simple app, that is supposed to read a policy number, and then display the results. I can't get it to read the file, or output onto the app. Any help would be appreciated.
    the file is called loans.txt and a line looks like this...
    12322|Smith, Dennis|456 Westfield Blvd|Westfield, IN 46033|$2,500|1/1/2001|7/11/2005|None
    public void GetFile(){
    //User's entered policy number is stored here
    String Policy_Num_Entered = SearchFor.getText();
    /*If the the policy is found in loans.txt, sucess will be changed to 1,
    otherwise it will stay 0 and be used to output a "I'm Sorry message*/
    int sucess = 0;
    //Try Catch Block
    try{
    BufferedReader br = new BufferedReader(new FileReader(file));
    //Access the first line of loans.txt
    String line = br.readLine();
    //Read the # of lines in loans.txt
    LineNumberReader read = new LineNumberReader(new FileReader(file));
    //Assign the # of lines to count
    int count = read.getLineNumber();
    //Item being looked by the String Tokenizer
    String Item;
    //For loop, looping the # of times a line must be read
    for(int x = 0; x < count; x++){
    //While Line is not empty, proceed
    while ( line != null )
    //Read individual words of the line from loans.txt
    StringTokenizer tokenizer = new StringTokenizer(line, "|");
    Item = tokenizer.nextToken();
    //While the line has more words
    while(tokenizer.hasMoreTokens() )
    //If Word equals "The" add 1 tot he sum
    if(Item == Policy_Num_Entered){
    //Fill in policy Number
    Policy_Number.append(Item);
    Item = tokenizer.nextToken();
    //Fill in First and Last Name
    Name.append(Item);
    //Item = tokenizer.nextToken();
    //Name.append(" " + Item);
    Item = tokenizer.nextToken();
    //Fill in Address
    Address.append(Item);
    Item = tokenizer.nextToken();
    //Address.append(" " + Item);
    //Item = tokenizer.nextToken();
    //Address.append(" " + Item);
    //Item = tokenizer.nextToken();
    //Fill in City, State and Zip Code
    City_St_Zip.append(Item);
    Item = tokenizer.nextToken();
    //City_St_Zip.append(" " + Item);
    //Item = tokenizer.nextToken();
    //City_St_Zip.append(" " + Item);
    //Item = tokenizer.nextToken();
    //Fill in Loan Balance
    LoanBal.append(Item);
    Item = tokenizer.nextToken();
    //Fill in Loan Effective Date
    LoanEffDate.append(Item);
    Item = tokenizer.nextToken();
    //Fill in Maturity Date
    MatDate.append(Item);
    Item = tokenizer.nextToken();
    //Take all the words that are left to fill in Notes
    //while(tokenizer.hasMoreTokens() ){
    Notes.append(" " + Item );
    Item = tokenizer.nextToken();
    //end of while has more tokens
    //Item found so change to 1
    sucess = 1;
    //Break out of the loop
    break;
    }//end of If
    //Grab the next word
    Item = tokenizer.nextToken();
    }//end of while tokenizer
    }//end of while
    //Read the next line
    line = br.readLine();
    }//for loop
    if(sucess == 0)
    JOptionPane.showMessageDialog(Finalapp.this, "I'm sorry the Policy " +
    Policy_Num_Entered + " was not found. Please try "+
    "again.");
    //Close the buffered Reader, and close the .dat file
    br.close();
    }//End of try
    //Catch any errors that may have occured in the reader
    catch(IOException exception)
    exception.printStackTrace();
    }//end of catch
    }//end of GetFile

    Ok I know that my line reader was messing up, so it was never running the loop, my new code reads like this...
    public void GetFile(){
    //User's entered policy number is stored here
    String Policy_Num_Entered = SearchFor.getText();
    /*If the the policy is found in loans.txt, sucess will be changed to 1,
    otherwise it will stay 0 and be used to output a "I'm Sorry message*/
    int sucess = 0;
    //Try Catch Block
    try{
    BufferedReader br = new BufferedReader(new FileReader("loans.txt"));
    /*FileInputStream file = new FileInputStream("c:\\loans.txt");
    BufferedReader br = new BufferedReader( new InputStreamReader( file) );*/
    //Access the first line of loans.txt
    String line = br.readLine();
    //Read the # of lines in loans.txt
    LineNumberReader read = new LineNumberReader(new FileReader("loans.txt"));
    //Assign the # of lines to count
    int count = 7;//read.getLineNumber();
    Policy_Number.append(count + " ");
    //Item being looked by the String Tokenizer
    String Item = null;
    //For loop, looping the # of times a line must be read
    for(int x = 0; x < count; x++){
    //While Line is not empty, proceed
    while ( line != null )
    //Read individual words of the line from loans.txt
    StringTokenizer tokenizer = new StringTokenizer(line, "|");
    Item = tokenizer.nextToken();
    //While the line has more words
    while(tokenizer.hasMoreTokens() )
    //If Word equals "The" add 1 to the sum
    if(Item == Policy_Num_Entered){
    //Fill in policy Number
    Policy_Number.append(Item);
    Item = tokenizer.nextToken();
    //Fill in First and Last Name
    Name.append(Item);
    Item = tokenizer.nextToken();
    //Fill in Address
    Address.append(Item);
    Item = tokenizer.nextToken();
    //Fill in City, State, ZIp Code
    City_St_Zip.append(Item);
    Item = tokenizer.nextToken();
    //Fill in Loan Balance
    LoanBal.append(Item);
    Item = tokenizer.nextToken();
    //Fill in Loan Effective Date
    LoanEffDate.append(Item);
    Item = tokenizer.nextToken();
    //Fill in Maturity Date
    MatDate.append(Item);
    Item = tokenizer.nextToken();
    //Take all the words that are left to fill in Notes
    Notes.append(" " + Item );
    Item = tokenizer.nextToken();
    //Item found so change to 1
    sucess = 1;
    //Break out of the loop
    break;
    }//end of If
    //Grab the next word
    Item = tokenizer.nextToken();
    }//end of while tokenizer
    //Read the next line
    line = br.readLine();
    }//end of while
    }//for loop
    if(sucess == 0)
    JOptionPane.showMessageDialog(Finalapp.this, "I'm sorry the Policy " +
    Policy_Num_Entered + " was not found. Please try "+
    "again.");
    //Close the buffered Reader, and close the .dat file
    br.close();
    }//End of try
    //Catch any errors that may have occured in the reader
    catch(IOException exception)
    exception.printStackTrace();
    }//end of catch
    }//end of GetFile

  • How to read data simultaneo​usly from different cdaq modules?

    Is there a way to synchronize input from separate cdaq modules?
    I need to read a voltage on an NI-9219 analog input channel and a
    frequency on an NI-9211 channel.  As far as I can tell a single "task" can
    only read input from channels on one module. Is there a way to build a task that reads data from multiple modules?
    Seems to me that buffered input is useless when multiple tasks are employed. With multiple tasks you get arrays of data that are sequential, not simultaneous. Is this correct? I'm thinking that the only way to
    get synchronized readings is to read each channel individually inside a
    loop. But this restricts the program to low speed data
    acquisition with  measurements that are spaced unevenly. Right?
    I want to create a data file with three columns: time, voltage,
    frequency. What's the best way to get these readings at the same
    instant?
    Referrence to a help document or tutorial would be great.
     thanks! 

    Synchronizing measurements of different types using separate cDAQ modules can be done by making sure that the physical channels for each module IO control are selected (and separated by commas). Please review the following Developer Zone article illustrating how this can be accomplished. Cheers
    1. NI-DAQmx: NI CompactDAQ Module Synchronization:  http://zone.ni.com/devzone/cda/epd/p/id/5259
    Regards,
    Ali M
    Applications Engineer
    National Instruments

  • Server Socket does not read data input stream

    Hi all,
    I am very newbie to Java Network programming with sockets and multi-threading.
    But I am obliged to develop a chat system written in Applets which can be placed on the website and used by visitors who come to my website.
    In order to understand this, I have tested a basic web chat program I downloaded from the Internet which use sockets and multi-threadings. The program work fine, no bugs at all at both compilation and run time. I noticed that all three streams for Client side (i.e. first one is input stream used receiving data from User; the second one is socket input stream used for receiving data from Server socket, and the third is socket output stream used for writing data to server socket) were established. And the same, two socket streams (input & output) for Server side were also connected when running program giving right port number and IP address of the server.
    The problem is both server and client sockets do not read data using the following stream classes:
    1. DataStreamInput: I use input.readUTF() method
    2. or BufferedReader: I use input.readLine() method
    The example of the codes are below:
    private BufferedReader input = null;
    private PrintWriter output = null;
    private Socket socket = null;
    public void open() throws IOException
    {  input = new BufferedReader(new
    InputStreamReader(socket.getInputStream()));
    System.out.println("Server socket input stream was created, and");
    output = new PrintWriter(socket.getOutputStream());
    System.out.println("Server socket output stream was created");
    public void run()
    {  System.out.println("Server Thread " + clientPort + " running.");
    while (true)
    {  try
    System.out.println("Server is reading data from Client, wait...");
    String fromClient = input.readLine();
    System.out.println("Server received a message on " + clientPort + ".");
    catch(IOException ioe)
    {  System.out.println(clientPort + " ERROR reading: " + ioe.getMessage());
    server.remove(clientPort);
    stop();
    The problem is at the line: String fromClient = input.readLine(); in the run() method? What is wrong with the codes above?
    Note: I also try to use original codes which use readUTF() method in DataStreamInput class instead using readLine() in BufferedReader. Both methods dont read data from inputstream socket?
    I very appreciate any help/advice from experienced developers.
    Best regards

    Hi,
    Yes. The readLine() method hangs! After the test, the execuation of the program is stopped at the line of readLine() method; it does not pass it?
    There is no problem with writing to Server socket. After the test, the program pass through flush() method. Here is the code for writing to sever socket within ChatClient (client side socket) class:
    private BufferedReader input = null;
    private PrintWriter           output = null;
    public ChatClient(String serverName, int serverPort)
    {  System.out.println("Establishing connection. Please wait ...");
    try
    {  socket = new Socket(serverName, serverPort);
    System.out.println("Connected: " + socket);
    start();
    catch(UnknownHostException uhe)
    {  System.out.println("Host unknown: " + uhe.getMessage()); }
    catch(IOException ioe)
    {  System.out.println("Unexpected exception: " + ioe.getMessage()); }
    public void start() throws IOException
    {  input   = new BufferedReader (new
                             InputStreamReader(System.in));
    System.out.println("Client User input stream was created,");
    output = new PrintWriter(socket.getOutputStream());
    System.out.println("Client Socket output stream was established, and");
    if (thread == null)
    {  client = new ChatClientThread(this, socket);
    thread = new Thread(this);
    thread.start();
    public void run()
         while (thread != null) {
         String fromUser;
              try{
                   while((fromUser = input.readLine())!= null)
                   System.out.println("Client wasreading a data from User, and");
    output.println(fromUser);
         output.flush();
         System.out.println("Client has written a data to Server");
    catch(IOException ioe)
    {  System.out.println("Sending to server error: " + ioe.getMessage());
    stop();
    etc.
    Here is a piece of codes for reading data from the Client Socket in the ChatServer Class (Server Side socket):
    public void run()
    {  System.out.println("Server Thread " + clientPort + " running.");
    while (true)
    {  try
    {  //server.handle(clientPort, input.readLine());
    System.out.println("Server is reading data from Client, wait...");
    String fromUser = input.readLine();
    //while((fromUser = input.readLine()) != null)
         System.out.println("Server received a message on " + clientPort + ".");
    catch(IOException ioe)
    {  System.out.println(clientPort + " ERROR reading: " + ioe.getMessage());
    server.remove(clientPort);
    stop();
    etc. Please advice why the readLine() method hangs; does not read data from the input stream received from the CLIENT?

  • Buffered Reader question.

    I am writing a program that reads data from multiple text files.
    When the program would need to read data from a different file I just reasigined the Buffered Reader object. For example:
    reader = new BufferedReader(new FileReader(new File(<name of first file>)));
    reader = new BufferedReader(new FileReader(new File(<name of second file>)));
    Is this a good method to use, or is it better to instanciate a new buffered reader object for each file?

    It is fine, the old reader will be GCed after a while.
    However, you might want to close the stream before just dumping the old one, as OSes have a limit on the number of files an app can open at one time. Plus it might leave the file locked, so other apps can not use said file.

  • Buffered Reader Question about wrapping around another Reader

    I'm reading about BufferedReaders and in the API the following paragraph reads:
    In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,
    BufferedReader in = new BufferedReader(new FileReader("foo.in"));
    I was wondering if somebody could explain their reasoning in slightly less complicated terms...I can't really figure out what their reasoning is. Thanks

    If every time you wanted to read a character, you had to talk to the hard disk device, it would be very slow. This is because communicating with the disk is thousands of times slower than communicating with main memory.
    The buffered reader reads in chunks, buffers those data, and allows you to request them one character at a time.

  • Buffered Reader from  a JTextArea?

    Hi everyone,
    can anyone please tell me how i can get a buffered reader from a JTextArea? This is what I would like to do where the following gets displayed in the JTextArea
    Please enter your name: (user enters data here)
    Please enter your id number: (user enters id number here)
    I had coded this using the System.in but now trying to convert to a GUI
    Regards,
    M

    Hi there,
    I can't use get text as I will already have the other data that is written in the text area there as well, so it will get all the text. I need to be able to write stuff and then read the next line from what I have written. For example using my the command prompt:
    static BufferedReader br = new BufferedReader(
                                                     new InputStreamReader(System.in));
    System.out.print("Enter choice : ");
                System.out.flush();
                String choiceStr=null;
                try
                    choiceStr = br.readLine();
                } catch (IOException ioe)
                    System.out.println("Error reading choice.");
                    System.exit(1);
                int choice = -1;
                if (choiceStr.length() > 0)
                    choice = Integer.parseInt(choiceStr);
                switch (choice)
                    case 0: ....
                }On screen it would have wrote Enter choice: (user puts "7" )
    when the 7 and then /r is pressed then it will read in the 7 only.
    Thanks, M

  • Buffered Reader IO

    Hi Friends,
    Have a unusual problem.
    I am trying to read a file using buffered reader api as:
    testHandle = new BufferedReader(new FileReader("Test.DAT"));
    but when i do
    while(...){
    String line = testHandle.readLine();
    System.out.println(line);
    the output is :
    My Name is Vishal.
    ello
    When in the file Test.DAT it is :
    # My Name is Vishal.
    Hello
    and if i add * in the Test.DAT file like this
    *# My Name is Vishal.
    Hello
    Then It prints
    # My Name is Vishal.
    ello
    Not able to understand why it is skipping the first letter (zeroth character of every line from the file) .
    Need your help on this.
    Thanks,
    Vishal

    You must be skipping some character(s), which you're not showing in the code snippet you posted. File I/O doesn't just skip over them - so there must be a bug in your code which you have omitted here.

  • Problems with buffered reads, buffers

    I have a few questions and issues that I have not been able to resolve with forum searches, I will try to keep them concise here.  #1 is the most important one to me.
    LabVIEW 7.1, Windows XP.
    Buffered Reads / Lost Data
    When error 10846 (AI Buffered Read, app unable to retrieve data from background acquisition buffer fast enough) occurs, I receive no data from the AI Buffered Read function for a period of time.  The error states data may be lost but it seems like I get NO data.  See the attached VI and JPG for examples.  The bottom graph shows a normal read while the top graph shows one with this problem.  I realize the AI Read error cluster is not handled in the acquisition loop.  From watching the backlog while the program runs, it seems the “dead spots” occur after the backlog reaches the buffer size.  When stopping acquisition, sometimes the error handler outside the loop reports 10846, sometimes it doesn’t (when the dead spots are occurring).  I can exaggerate dead spots with setups as follows:
      Buffer size 5, Scan rate 1000, # Scans to read 100
      Buffer size 10000, Scan rate 5500, # Scans to read 100
    The size of the dead spots and continuous data are proportional to the buffer size.
    Questions....
    1. Shouldn’t the AI Read function wait until it has # scans to read of valid data before returning?  For instance, scan rate of 100 and # scans to read of 1000 slows loop iteration speed to 0.1 Hz.  It seems like it is returning nothing for a period of time after the backlog reaches the buffer size.
    2. Error 10846 refers to the “data acquisition buffer.”  Is this the software buffer?  If so, what would LV refer to the hardware buffer as?
    3. I know the PCI-MIO-16E-1 has a hardware buffer, does this mean I can accurately acquire data over a period of time at a specified frequency (within limitations of the card of course) without having to worry about Windows bogging down due to delayed writes and such?
    4. Will hardware acquisition buffers generate an error if the data in them is lost/overwritten?
    5. I tried loading the acquisition VI (attached) onto a LV computer that has only a new USB-6008 connected but the AI read/config/clear functions were not available on that system.  Does this device not have hardware buffers (either I’m looking in the wrong places to find the answer this question and it uses different VIs OR it doesn’t have them). 
    6. The buffer/scan configuration listed above was used to exaggerate error 10846 and the accompanying dead spots but this problem has been intermittently plaguing a system I have been trying to understand/fix.  I have logged the backlog value as the program runs and see that it increases during certain processor-heavy state machine states and am hoping upgrading from 256MB to 2GB RAM will improve this.  Is there any reason I should not look at this as a solution?  (I am also planning on adding an error handler for AI Read into each acquisition loop so the problem can not continue to go on without detection!!!!!!!!!)
    7. Shouldn’t the AI Clear function report an error from the AI Read error cluster, even if it happened several reads earlier?  It seems like it does not do this; if I put the error handler in the acquisition loop I receive an error as soon as the backlog reaches the buffer size, EVERY time.  I thought I figured this out and changed the acquisition loop tunnels to shift registers... the error is reported each time this way; if AI Read will not acquire data if an error is fed into it in the first place then I guess I understand this one so I’m moving it to the bottom of the list.
    Thank you all for your time, I have been struggling to get up to speed with DAQ and LV and appreciate all the support.  I look forward to giving back to NI’s community in the future. 
    Regards,
    David.

    After all that typing I forgot the attachements, they should be on this post.
    I take it the AI.llb functions are "traditional DAQ."  I've started to experiment with the express VIs with newer hardware that I have been working with (USB-6008, USB-6211).  I will have to look at the DAQmx functions, it seems the express VIs are frowned upon by most.
    I have been working on modifying an older program that uses the traditional DAQ functions.  I will have to get more comfortable with DAQmx before attempting to change it over to them.  The attached example was wrote as I tried to understand what was going on in the program I was modifying.
    I believe the missing error handler on the AI Read function was causing unexpected (i.e. nothing returned) results the next time AI Read was called when the backlog exceeded the buffer value.  Subsequent calls to AI Read worked as expected unless the buffer overflowed again.
    Assuming this is correct the hardware buffer is the only thing I would like to understand better.  If it overflows what error (if any) will be generated in LV? 
    The other questions can be chalked up to the way traditional DAQ functions work and I think I've chased my tail enough to figure that out.
    Thanks,
    David.
    Attachments:
    acquire.jpg ‏25 KB
    acquire.vi ‏293 KB

  • Reading data froma an excel

    Hi all,
               I want to read data froma an excel sheet.
    The code i used to read the data is
    IWDAttributeInfo attributeInfo = wdContext.getNodeInfo().getAttribute(IPrivateFileUplaodView.IContextElement.FILE_RESOURCE);
    *     IWDModifiableBinaryType binaryType = (IWDModifiableBinaryType) attributeInfo.getModifiableSimpleType();*
    *                    IContextElement element = wdContext.currentContextElement();*
    *                    if(element.getFileResource()!= null)*
    *                      try*
    *                            String mimeType = binary.getMimeType().getFileExtension();*
    *                            wdComponentAPI.getMessageManager().reportSuccess("File " + binaryType.getFileName() + " has been successfuly uploaded ! ");*
    *                      catch(Exception e)*
    *                            throw new WDRuntimeException(e);*
    *                    else*
    *                         wdComponentAPI.getMessageManager().reportException("File could not be uploaded", true);*
    *                    // Till here the code remains the same as in File Upload tutorials*
    *                    // Now the code for retrieving the values from the Excel sheet*
    *                    try*
    *                       ByteArrayInputStream bais = new ByteArrayInputStream(element.getFileResource());*
    *                       Workbook workbook = Workbook.getWorkbook(bais);*
    *                       Sheet sheet = workbook.getSheet(0);*
    *                       Cell a1 = sheet.getCell(0,0);*
    *                       Cell a2 = sheet.getCell(0,1);*
    *                       wdComponentAPI.getMessageManager().reportSuccess("Value of cell a1 = " + a1.getContents());*
    *                       wdComponentAPI.getMessageManager().reportSuccess("Value of cell a2 = " + a2.getContents());*
    *                    catch(Exception ex)*
    *                      wdComponentAPI.getMessageManager().reportException(ex.getLocalizedMessage(),true);*
    But i am getting error at "binary" in  String mimeType = binary.getMimeType().getFileExtension();
    and ByteArrayInputStream bais = new ByteArrayInputStream(element.getFileResource()); by saying that there is no constructor of
    ByteArrayInputStream with Resource as parameter.
    Please let me know what might be the issue so that i can solve this.
    Thanks and regards,
    Chandrashekar.

    Hi,
    Replace the following code
    ByteArrayInputStream bais = new ByteArrayInputStream(element.getFileResource());*
    with
    IWDResource resource = element.getFileResource();
           InputStream inputStream = resource.read(false);
           ByteArrayInputStream bais = new ByteArrayInputStream(inputStream);
    Regards
    Ayyapparaj

Maybe you are looking for