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

Similar Messages

  • Why does saving text from a jtextarea to a text file result in....?

    one long string that includes square blocks when the new line should be?
    Why can't I read normal text from a text file. It looks like i have to save it first for it to be read.
    Also why is it that my application succesfully reads and displays the contents of a text file that i just saved but when i manually open that file I don't see it. All i can see is what the text that i manually entered into the text file.
    I use a buffered reader so wondered if there was some caching but have no idea.

    one long string that includes square blocks when the new line should be? If you use something like:
    write(textArea.getText())
    then "\n" will be written to the file as a newline string, but on a Windows platform the newline string is "\r\n".
    You should be using the read(...) and write(...) methods of the JTextArea and the newline string will be handled correctly.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    class TextAreaLoad
         public static void main(String a[])
              final JTextArea edit = new JTextArea(5, 40);
              JButton read = new JButton("Read some.txt");
              read.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        try
                             FileReader reader = new FileReader( "some.txt" );
                             BufferedReader br = new BufferedReader(reader);
                             edit.read( br, null );
                             br.close();
                             edit.requestFocus();
                        catch(Exception e2) { System.out.println(e2); }
              JButton write = new JButton("Write some.txt");
              write.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        try
                             FileWriter writer = new FileWriter( "some.txt" );
                             BufferedWriter bw = new BufferedWriter( writer );
                             edit.write( bw );
                             bw.close();
                             edit.setText("");
                             edit.requestFocus();
                        catch(Exception e2) {}
              JFrame frame = new JFrame("TextArea Load");
              frame.getContentPane().add( new JScrollPane(edit), BorderLayout.NORTH );
              frame.getContentPane().add(read, BorderLayout.WEST);
              frame.getContentPane().add(write, BorderLayout.EAST);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • HOW TO WRITE AND READ FROM A TEXT FILE???

    How can I read from a text file and then display the contents in a JTextArea??????
    Also how can I write the contents of a JTextArea to a text file.
    Extra Question::::::: Is it possible to write records to a text file. If you have not idea what I am talking about then ignore it.
    Manny thanks,
    your help is much appreciated though you don't know it!

    Do 3 things.
    -- Look through the API at the java.io package.
    -- Search previous posts for "read write from text file"
    -- Search java.sun.com for information on the java.io package.
    That should clear just about everything up. If you have more specific problems, feel free to come back and post them.

  • Getting the text from a JTextArea...

    hi, I'm making a perfect calculator program and I'm trying to add a Note Pad function to it, I also want to hide that so the other interface can be used; I can get it hided and come again but I'm wondering how could I get the text from the JTextArea INCLUSIVE the enters that are made withing it, so:
    theString = jTextArea1.getText();only gives me the text and no enters; suggestions?

    I think I displayed it wrongTwo things to keep in mind...
    Certain Swing components will just ignore newlines, so you have to be careful where/how you're displaying your multiline text strings. Some components will display it all as one line, some will only display the top line, some will even show \n instead of doing the newline. It all just depends.
    And JTextArea does support word wrapping, so just because it looks like there's a newline, there may not be one.

  • Trying to read from a socket character by character

    Hi all,
    I have a problem with reading from a socket character by character. In the code shown below I try and read each character, and then write it to a file. The information sent to a socket sent from a file, and EOF is marked with character of ascii code 28 (file separator). However using BufferedReader.read() I get -1 forever. Is it reading only the last character to have been sent to the socket?
    As a side note, if I use readLine() (making sure the socket is sent a newline at end of msg) I can get the message fine. However, I want to be able to receive a message with 0 or many newlines in it (basically contents of a text file), so I want to avoid the readLine() method.
    Any help at all is appreciated,
    Colm
    CODE SNIPPET:
    try
    serverSocket = new ServerSocket(listenToPort);
    System.out.println("Server waiting for client on port " + serverSocket.getLocalPort());
    while(true)
    inSocket = serverSocket.accept();
    System.out.println("New connection accepted " + inSocket.getInetAddress() + ":" + inSocket.getPort());
    input = new BufferedReader(new InputStreamReader(inSocket.getInputStream()));
    fileOutput = new BufferedWriter(new FileWriter(outputFilename));
    System.out.println("Ready to write to file: " + outputFilename);
    //receive each character and output it to file until file separator arrives
    while(!eof)
    inCharBuf = input.read();
    System.out.print(inCharBuf);
    //check for file separator (ASCII code 28)
    if (inCharBuf == 28) eof = true;
    //inChar = (char) inCharBuf;
    fileOutput.write(inCharBuf);
    System.out.println("Finished writing to file: " + outputFilename);
    inSocket.close();
    catch (IOException e)
    System.out.println("IO Error with serverSocket: " + e);
    System.exit(-1);
    }(tabbing removed as it was messing up formatting)

    My guess is that the code that is writing to the
    socket did not flush it. You said in one case you
    could read it (via readln) if the writer was writing
    lines (writeln flushes, I believe). Are you writing
    the exact same data to the socket in both tests?woo hoo, I hadn't flushed the buffers alright!
    for anyone with similar problems, I was missing this from my write-to-socket method:
    output.flush();
    where output was the BufferedWriter I had created to write to the socket.
    Thanks a lot for pointing it out!
    Colm

  • HELP!! ERROR IN reading from file!! (PART of )PROGRAM

    Take a look at my program first....
    import java.io.*;
    public class reading_file {
    public static void main(String[] args) throws IOException {
    BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
    String [] sType= new String[10];
    int [] sNum= new int[10];
    float [] sPrice= new float[10];
    String FileName="new.txt";
    BufferedReader inFile=new BufferedReader(new FileReader(FileName));
    String inputLine="";
    int totalLines=0;
    while(inFile.readLine()!=null){
    totalLines++;
    int totalStock=totalLines/3;
    System.out.println(totalStock);
    for(int i=0; i<totalStock;i++){
    sType=inFile.readLine();
    System.out.println(sType[i]);
    sNum[i] =Integer.parseInt(inFile.readLine());
    System.out.println(sNum[i]);
    sPrice[i] =Float.parseFloat(inFile.readLine());
    System.out.println(sPrice[i]);
    inFile.close();
    I am reading the info from the file to the respective array shown.
    e.g these are the info in the .txt file
    /////=>
    PANTS
    35
    23.3
    LOGITECH CORDLESS DESKTOP
    200
    50.23
    MONITER
    62
    54.9
    <=
    but when i run the program the errors such as :
    ==>
    compile-single:
    run-single:
    3
    null
    Exception in thread "main" java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:415)
    at java.lang.Integer.parseInt(Integer.java:497)
    at reading_file.main(reading_file.java:26)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)
    why is that??
    any mistake in the program??

    You could mark the start of the file with the mark method from BufferedReader, but you'd best check that this is ok to do with a call to the bufferedreader markSupported method. This method will return true if you are able to mark the reader. You have to include an int parameter with the mark method that is bigger than the file size. In your case this will be easy since the file is small. Then before the second reading, call reset( ) on your buffered reader.
    Personally, I wouldn't use arrays but would use an arraylist. Also, I'd have the 3 bits of information entered into a single object and store all the information (contained within the single object) into a single arraylist. Since the arraylist has a variable size, you don't need to know its size in advance, and you don't have to worry about reading through a file twice. Once will do nicely.

  • 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.

  • Getting a single line from a JTextArea

    I have a JTextArea with a fixed size. I've used the .setLineWrap(true) and .setWrapStyleWord(true) on this JTextArea, so when the user types in some text, that's longer that the JTextArea, it will wrap unto the next line. I need to get each visible line from the JTextArea. That is not each line of text, that is seperated by a newline (when the user type Enter), but every line, that is visibly seperated in the JTextArea.
    How can i do that.

    The javax.swing.text.Utilities class can help:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class TestUtility extends JFrame
         public TestUtility()
              final JTextArea textArea = new JTextArea( "one two three four five", 5, 10 );
              textArea.setLineWrap( true );
              textArea.setWrapStyleWord( true );
              JScrollPane scrollPane = new JScrollPane( textArea );
              getContentPane().add( scrollPane );
              textArea.addCaretListener( new CaretListener()
                   public void caretUpdate(CaretEvent e)
                        int pos = textArea.getCaretPosition();
                        try
                             int start =  Utilities.getRowStart(textArea, pos);
                             int end =  Utilities.getRowEnd(textArea, pos);
                             System.out.println( start + " : " + end );
                        catch (BadLocationException ble) {}
         public static void main(String[] args)
              TestUtility frame = new TestUtility();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);

  • Read from a file continuously

    Hello all.
    I wonder if there is an easy way to read from a file so that the currect contents of the file are always available within a Java program.
    For instance:
    1. The file "text.txt" has one line: "hello"
    2. Open the file from a Java program; it has the line "hello"
    3. Somebody adds another line to the file: "bye"
    4. The Java program is noticed about 3. so that the line "bye" can be read
    Something like "tail -f" or a named pipe (fifo) in Unix.
    Thanks in advance.
    God bless,
    Jaime

    No, this is NOT a solution. Once FileReader has encountered an EOF condition once, it will never go back to the file descriptor to see if there might be some more available. (For that reason, also reader.ready() will never return true again, no matter how much is appended to the file.) I tried this on Java 1.5.0_11 on Solaris.
    The other proposed solution, checking the file length periodically using the File length() method and then re-opening the file if the length is different, is also seriously flawed for several reasons:
    (a) If the file is renamed, you have no way of telling whether the file you already opened is modified -- the next time you call file.length(), it would fail since the old name doesn't exist any more, or, even worse, if meanwhile a new file was created under the old name, you'd be looking at a different file, not the one you've opened for reading!
    (b) If you do detect a change, having to reopen the file as a RandomAccessFile to be able to seek to the last read position is bad because you have to implement your own buffering (can't wrap BufferedReader around it, obviously), AND it suffers from the same file rename problem! The file you re-open might be a different one, so seeking to the last read position would land you at an arbitrary spot in a different file, and you wouldn't even know it!!!
    As a conclusion, it is apparently not possible to implement something as elementary as "tail -f" in Java correctly!
    Someone will have to think about that. Yes, I saw the argument that this may not be implementable on ALL kinds of file systems and hence not portable, but just because Windows file handling is broken, this shouldn't mean that Java file handling has to be broken on all decent platforms as well!
    :-(

  • 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

  • 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);
    }

  • Bytes read from Socket buffer

    Hi,
    I'm writing a proxy application that relays data from a server to a client that requested the data. One thing I have observed is that when I have read about 32136 bytes of data, my reads from my buffered input stream fetch only one byte at a time. Not only is my read function now reading only one byte at a time, but it takes over a minute to fetch 83 bytes of data. And the delay gets worse the longer I run.
    In an effort to stress test my app, I deliberately set the send and receive buffers of the client socket to a small value (128 bytes). I can understand that filling up the buffer could slow down the reading, but what is odd is that long after the client has digested all the data, the Input stream reads never seem to go back to their original speed.
    Is this an O/s thing? a JVM thing? I'm running JDK 1.3.1 on an intel box with Linux Redhad 6.2. It seems to me that there must be some way of getting the socket buffer clear on the receive side so that I can get something that ressembles a normal dataflow. Oh, and I tried toggling the TCP no delay flag to no avail.
    Any suggestions?
    -hugh

    However, even with a large socket buffer, there is
    always the chance that the receiving app will run
    slowly due to bad programming, network latency, etc
    (we're not the authors of the clients who will
    connect), meaning even with the maximum buffer size,
    we could fill the socket buffer. I suppose, though,
    if it is the sender app that is getting fooled, then
    it's a matter for the authors of the sending
    application.True but the same thing will happen if the client connects directly to the server without your proxy, so why worry? General tips for writing proxies: use as large a buffer as possible, run separate reading and writing threads in your proxy, and propagate an EOF by doing shutdownOutput in the opposite direction. When you have done this in both directions you can close the socket, not before.

  • 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.

  • How read from CD?

    Hi,
    I m new to swing and hope somebody can help me. I want to read from CD drive when click on a button. How can i do this ?
    thanks in advance

    well, the code sample i sent you, works fine. When i click on a button, this little code runs. The dialog box opens, showing directories somewhere in my C drive. The rest of the code is not relevant to what i need here, because its just a sample piece of code. (when users selects a file ,it adds name of the file to a JTextArea).
    But what i need is, to show the contents of CD ROM drive when this dialog box is opened! I do not want user to select CD ROM drive from this dialog box. When dialog box opens, the contents of CDROM should be in there. I googled but could not find a way to implement what i need.
    Hope you can guide me.

  • 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.

Maybe you are looking for