Bug in BufferedReader

HI
I'm writing a webserver with java,it works for text and html files but sends a bad image when an image is requested.
I think bufferedreader has some problems,i tested it and i found that the readed string is not equal to real one.
my code is something like it:
BufferedReader reader = new BufferedReader(new FileReader("a file name"));
int status = 0;
char[] rd = new char[256];
while( status != -1 ){
status = reader.read(rd);
for(int i=0; i<status; i++){
out.print(rd);
reader.close();
where out is my output stream.
what is your idea about that?
thanx.
--Mona                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

I tried it, and i used read(byte[]) but it sends an
String of bytes instead of an image(i mean IE shows an
String of bytes)
what should i do?That means you've set your content type incorrectly.
- K

Similar Messages

  • URGENT!! - Bug on read (readLine) method?

    Hello to all, I have need of a large aid.
    I need to know if There is the possibility that the method read() or readLine(), than I use for reading data from a socket from a PLC, has a Bug.
    This why, with the socket opened and of the data in arrival from the PLC (than does not give to errors), the method read() raises the "Connection exception reset by peer."
    The Technicians of the PLC say not to have errors but and I am surest of the correct operation of the server socket, also why it has been tested with telnet, hyperterminaly and others client without problems.
    I do not know that what to say and what to try.
    Thanks for every eventual aid.

    I don't think there is a bug with BufferedReader. But instead of using buffered reader, you can try using the socket input stream directly for reading to see if it makes any difference:
    try {
      // if the PLC is a client:
      ServerSocket serverSocket = new ServerSocket(...);
      Socket socket = serverSocket.accept();
      // or if the PLC is a server:
      Socket socket = new Socket(...);
      // and the rest of the code to test with
      InputStream in = socket.getInputStream();
      byte[] buffer = new byte[1024];
      int length;
      while ((length = in.read(buffer)) != -1) {
        System.out.println("Read "+length+" bytes");
      System.out.println("Connection closed");
    } catch (Exception e) {
      e.printStackTrace();
    }See if that little example works.
    Is the PLC i client or server? Is the PLC the first to write something to your java program or do you have to write something to it first (maybe it doesn't understand what you write to it).
    If you use reader/writer classes, there could be problems with the character encoding you use. If you don't specify any with InputStreamReader/OutputStreamWriter, then you will use the default platform encoding. I don't know which character encoding the PLC use, but if the characters are between 0 and 255, and you really want to use reader and writer classes, then use the ISO 8859-1 encoding.

  • Bug with InputStream.read after BufferedReader.readLine in a Thread ?

    I just found something strange when reading bytes on a socket after reading lines.
    I'll show you an example :
    In this example, when a connexion is established, I launch a thread where a single line of String then 3 bytes are read from the socket. I use BufferedReader.readLine for the String line then just InputStream.read to read the 3 bytes.
    The results are quite random. Sometimes it works, sometimes not (most times it doesn't)... it seems to always work under linux (but haven't tested it as many times than on windows). Most of the time the program is stuck on the "socket.getInputStream().read(bytes);" line with 0 bytes available. I tried to do the same thing outside of a thread, I thought it worked better beaucause I was able to run it without any problem but it doesn't work anymore when I test it again.
    I can't say if I'm doing something wrong or if it's a java bug (I've got JDK 1.6.0_03-b05).
    Can you please have a look a this little example and maybe test it and let me know if it works or not. I tried to code my own readLine function and it seems to work with it but I'd like to know if it's a bug or what. Thank you.
    Server side :
    import java.io.*;
    import java.net.*;
    public class testServer extends Thread {
         private Socket socket;
         public testServer(Socket testSocket)
              socket = testSocket;
         public void readData() throws Exception
              BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              String str;
              str = br.readLine();
              System.out.println(str);
              System.out.println("Bytes available : " + socket.getInputStream().available());
                    //Try to read the bytes
                    byte[] bytes = new byte[3];
                    //STOPS THERE UNDER WINDOWS, BUT WORKS WITH LINUX
              socket.getInputStream().read(bytes);
                    //Simple "ack" to say to the client that he can close the connexion
              socket.getOutputStream().write(0);
              socket.getOutputStream().flush();
                    //Print the bytes values
              for(byte value : bytes)
                   System.out.println(value);
         public void run()
              try {
                   readData();
              } catch (Exception e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              try {
                   ServerSocket welcomeSocket = new ServerSocket(3333);
                   while(true)
                        new testServer(welcomeSocket.accept()).start();
              } catch (Exception e) {
                   e.printStackTrace();
    }client side :
    import java.io.*;
    import java.net.*;
    public class testClient {
         public static void main(String[] args) {
              try {
                            //Some test values
                   byte[] testValues = new byte[]{1,2,3};
                   Socket socket = new Socket(InetAddress.getLocalHost(), 3333);
                            //Send the line through the socket
                   BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                   bw.write("HELLO WORLD\r\n");
                   bw.flush();
                            //then the bytes
                   socket.getOutputStream().write(testValues);
                   socket.getOutputStream().flush();
                            //Just waits for the server's ack to close the connexion
                   socket.getInputStream().read();
                   socket.close();
              } catch (Exception e) {
                   e.printStackTrace();
    }

    It's your bug.
    When you create a BufferedReader and ask it to read a line, the first thing it does is to read a whole buffer full of data (hence the name of the class) from its underlying input stream. That's probably about 4000 characters or something like that. It stores that internally and then starts doling it out in response to calls to readLine() and so on.
    Then when you go back to reading from the underlying input stream, those 4000 or so characters are already gone from it. You have no access to the data the BufferedReader is hanging on to this way. All you can do is to start reading at the point after that whole buffer, which is not what you want.

  • A little help maby??? (Find the bug)

    I made a part of a prog but there's a bug in it, plz help me...
    import java.util.*;
    class DobbelSteen
         Random myRandom = new Random();
         int A()
              int randomNumberA = myRandom.nextInt(6);
              randomNumberA = randomNumberA + 1;               
              return randomNumberA;
         int B()
              int randomNumberB = myRandom.nextInt(6);
              randomNumberB = randomNumberB + 1;
              return randomNumberB;
         int     teerling()
              int aantalOgen = B() + A();
              return aantalOgen;
    import java.io.*;
    import java.util.*;
    class Intro
              DobbelSteen dobbelsteen = new DobbelSteen();
              String player1, player2, a, b, data;
              Intro() throws IOException
                   BufferedReader stdin = new BufferedReader ( new InputStreamReader (System.in));
                   System.out.println("Welcome to MoneyPoley made by Thorrific and also a bit of Java.");
                   data = stdin.readLine();
                   System.out.println("When you wish to stop due to a bug or a loss, you enter: STOP");
                   data = stdin.readLine();
                   System.out.println("If I ask you something then plz answer with 'y' (yes) or 'n' (no).");
                   data = stdin.readLine();
                   System.out.println("Got it?");
                   data = stdin.readLine();
                   if ( data.equals("y") )
                        System.out.println("Thnxs, let us continue...");
                   else
                        System.out.println("Don't be a fucking dick and type what is asked!");
                        data = stdin.readLine();
                        System.out.println("I still control this game, until windows crashes..., which might happen :-]");
                        data = stdin.readLine();
                        System.out.println("Time to crash ;-) :p");
                        data = stdin.readLine();
                        int buy1 = 0;
                        while (buy1 < 50000)
                                  System.out.print("Crash");
                                  buy1 = buy1 + 1;
                        return;
                   data = stdin.readLine();
                   System.out.println("First let me know who player1 is:");
                   a = stdin.readLine();
                   System.out.println("Welcome "+a+".");
                   data = stdin.readLine();
                   System.out.println("What is the name of player2 ?");
                   b = stdin.readLine();
                   System.out.println("Also welcome "+b+".");
                   data = stdin.readLine();
                   System.out.println("Now let us decide who will start playing.");
                   data = stdin.readLine();
                   int A = dobbelsteen.A();
                   int B = dobbelsteen.B();
                   while ( A == B)
                        System.out.println(a+" throws a "+A+".");
                        System.out.println(b+" throws a "+B+".");
                        data = stdin.readLine();
                        System.out.println("Looks like we have to role again...");
                        System.out.println("Cause somebody managed to get equal numbers...");
                        data = stdin.readLine();
                        A = dobbelsteen.A();
                        B = dobbelsteen.B();
                   System.out.println(player1+" throws a "+A+".");
                   System.out.println(player2+" throws a "+B+".");
                   data = stdin.readLine();
              String player1()
                   if (dobbelsteen.A() > dobbelsteen.B())
                        player1 = a;
                        return player1;
                   else
                        player1 = b;
                        return player1;
              String player2()
                   if (dobbelsteen.A() > dobbelsteen.B())
                             player2 = b;
                             return player2;
                   else
                             player2 = a;
                             return player2;
              void hallo()
                   System.out.println(player1());
                   System.out.println(player2());
         class example
              public static void main (String[] args) throws IOException
                   Intro zzz = new Intro();
                   zzz.hallo();
    ----->>>>> There is something very wrong with the names, try this version a few times and you will find out, I hope you see what I'm trying to do...

    Why do you have a method called 'player1()' and a variable called 'player1'? And you never call the 'player1()' method.

  • Is it a bug in JDK1.3?

    Here's a simple program that I compiled and executed by using JDK1.3. The program had worked all very well as long as I typed in 'C' , 'P', 'N', 'A', 'b', or other single characters. Just by curiosity, I kept keying 'c' for 6 or 7 times and of course the computer kept telling me "Entry must be C or P or N!". After that, when I key in 'C', 'P', or 'N' again, strange things happened. I was still confronted with the same message as if I had keyed in invalid characters. The situation lasted until after I typed the command java ChooseManager. Then I got the correct response for the last 'C', 'P' or 'N' that I had entered. Is it a bug in JDK1.3?
    Here is the program:
    public class ChooseManager
    static final double CORP_RATE = 75.99;
    static final double PRI_RATE = 47.99;
    static final double NON_PROF_RATE = 40.99;
    public static void main(String[] args) throws Exception
         char eventType;
         Chap4Event anEvent;
         System.out.println("Enter type of event you are scheduling");
         System.out.println("C for a corporate event");
         System.out.println("P for a private event");
         System.out.println("N for non-profit event");
         eventType=(char)System.in.read();
         while(eventType != 'C' && eventType != 'P' && eventType != 'N')
              System.in.read(); System.in.read();
              System.out.println("Entry must be C or P or N!");
              eventType = (char)System.in.read();
         System.out.print("The manager for this event will be ");
         switch (eventType)
              case 'C':
              System.out.println("Dustin Britt");
              anEvent = new Chap4Event(eventType, CORP_RATE);
              break;
              case 'P':
              System.out.println("Carmen Lindsey");
              anEvent = new Chap4Event(eventType, PRI_RATE);
              break;
              default:
              System.out.println("Robin Armanetti");
              anEvent = new Chap4Event(eventType, NON_PROF_RATE);
              break;
         System.out.println("Event type is " + anEvent.getEventType());
         System.out.println("Minimum rate charged is $" + anEvent.getEventMinRate());

    HELP, jsalonen. Something wrong with Readerbuffer. Why complier state can't resolve class:reader, InputStreamReader and BufferedReader ? Must I input something first?
    public class PetAdvice
         public static void main(String[] args) throws Exception
              char resiType;
              char hour;
              System.out.println("Please cateory your residence type");
              System.out.println("'A' for apartment;");
              System.out.println("'H' for house;");
              System.out.println("'D' for dormiory;");
              Reader resiType = new InputStreamReader(System.in);
              BufferedReader in = new BufferedReader(reader);
              String inputLine = in.readLine();
              while(!(inputLine.equals("A") |
                   inputLine.equals("H") |
                   inputLine.equals("D")))
                   {   System.out.println("entry: "+inputLine+" Entry must be A or H or D");
              inputLine = in.readLine();
              System.out.println("Please specify the average hours you will spend at home.");
              System.out.println("A) 18 or more;");
              System.out.println("B) 10 to 17;");
              System.out.println("C) 8 to 9;");
    System.out.println("D) 6 to 7;");
              System.out.println("E) 0 to 5;");
              hour = (char)System.in.read();
              while (hour != 'A' && hour != 'B' && hour != 'C' && hour != 'D' && hour != 'E')
    System.in.read(); System.in.read();
                   System.out.println("Invalid input, pls choose again.");
                   resiType = (char)System.in.read();
    if (resiType == 'H' && hour == 'A')
    System.out.println("Our recommendation is Pot bellied pig");
              else if (resiType == 'H' && (hour == 'B' || hour == 'C'))
                   System.out.println("Our recommendation is Dog.");
              else if (resiType == 'H' && (hour == 'D' || hour == 'E'))
              System.out.println("Our recommendation is Snake.");
              else if (resiType == 'A' && (hour == 'A' || hour == 'B' ))
              System.out.println("Our recommendation is Cat.");
              else if (resiType == 'A' && (hour =='C' || hour == 'D' || hour == 'E'))
              System.out.println("Our recommendation is Hamster.");
              else if (resiType == 'D' && (hour == 'D' || hour == 'C' || hour == 'B' || hour == 'A'))
              System.out.println("Our recommendation is Fish.");
              else if (resiType == 'D' && hour == 'E')
              System.out.println("Our recommendation is Ant Farm.");
              else
                   System.out.println("Sorry, no recommendation currently.");

  • BUG: Oracle Java Compiler bug with anonymous inner classes in constructor

    The following code compiles and runs just fine using 1.4.2_07, 1.5.0_07 and 1.6.0_beta2 when compiling and running from the command-line.
    It does not run when compiling from JDeveloper 10.1.3.36.73 (which uses the ojc.jar).
    When compiled from JDeveloper, the JRE (both the embedded one or the external 1.5.0_07 one) reports the following error:
    java.lang.VerifyError: (class: com/ids/arithmeticexpr/Scanner, method: <init> signature: (Ljava/io/Reader;)V) Expecting to find object/array on
    stack
    Here's the code:
    /** lexical analyzer for arithmetic expressions.
    Fixes the lookahead problem for TT_EOL.
    public class Scanner extends StreamTokenizer
    /** kludge: pushes an anonymous Reader which inserts
    a space after each newline.
    public Scanner( Reader r )
    super( new FilterReader( new BufferedReader( r ) )
    protected boolean addSpace; // kludge to add space after \n
    public int read() throws IOException
    int ch = addSpace ? ' ' : in.read();
    addSpace = ch == '\n';
    return ch;
    public static void main( String[] args )
    Scanner scanner = new Scanner( new StringReader("1+2") ); // !!!
    Removing the (implicit) reference to 'this' in the call to super() by passing an instance of a static inner class 'Kludge' instead of the anonymous subclass of FilterReader fixes the error. The code will then run even when compiled with ojc. There seems to be a bug in ojc concerning references to the partially constructed object (a bug which which is not present in the reference compilers.)
    -- Sebastian

    Thanks Sebastian, I filed a bug for OJC, and I'll look at the Javac bug. Either way, OJC should either give an error or create correct code.
    Keimpe Bronkhorst
    JDev Team

  • BufferedReader.readLine() from a socket repeats input (JDK 1.4 beta/Win95)

    When I call BufferedInput.readLine(), and the data source is a socket, readLine()
    will return the most recent text indefinitely until the client sends more text.
    Isn't BufferedInput.readLine() supposed to clear the
    buffer with each readLine() call?
    Socket settings:
    getTcpNoDelay: false
    getSoLinger: 10
    getSoTimeout: 75
    getSendBufferSize: 8192
    getReceiveBufferSize: 8192
    Locations of complete source and output:
    http://www.nationalinformatics.com/download/SocketServerClientTest.java
    http://www.nationalinformatics.com/download/SocketServerTest_output.txt
    http://www.nationalinformatics.com/download/SocketServerTest.java
    http://www.nationalinformatics.com/download/SocketServerClientTest.java
    http://www.nationalinformatics.com/download/SocketServerClientThread.java
    </PRE>
    Sample output:
    SocketServerThread: readline loop.
    SocketServerThread: Input line is 'hello' (length: 5)
    SocketServerThread: input line was read
    SocketServerThread: readline loop.
    SocketServerThread: Input line is 'hello' (length: 5)
    SocketServerThread: input line was read
    . . . etc, until the client sends "Java Rules!" down the wire . . .
    SocketServerThread: readline loop.
    SocketServerThread: Input line is 'Java Rules!' (length: 11)
    SocketServerThread: input line was read
    SocketServerThread: readline loop.
    SocketServerThread: Input line is 'Java Rules!' (length: 11)
    SocketServerThread: input line was read
    . . . etc . . .
    Thread code that reads input from the client:
    import java.net.*;
    import java.io.*;
    import java.util.*;
    /** SocketServerThread is an independent thread that is used to test
        socket connections.
        <p>Copyright 2001 (c) Richard Schilling.  All rights reserved.
    class SocketServerThread extends Thread {
         private boolean running;
            private Socket socket = null;
            public SocketServerThread(Socket s, boolean r) {
                    socket = s;
              running = r;
            public void run() {
                    try {
                            // Create a reader to receive messages from the client
                            BufferedReader in = new BufferedReader(
                                     new InputStreamReader(socket.getInputStream())
                            String inputLine = null;
                            while ( running) {
                        System.out.println("SocketServerThread: readline loop.");
                        boolean lineread = false;
                        while (!lineread){
                             lineread = true;
                             try {
                                  inputLine = in.readLine();
                             } catch (InterruptedIOException e){
                                  lineread = false;
                                  System.out.println("SocketServerThread: Interrupted exception while reading from 'in'");
                             } catch (SocketException e){
                                  lineread = false;
                                  System.out.println("SocketServerThread: could not read input stream 'in'");
                        if (inputLine != null){
                             if (inputLine.length() > 0){
                                  String TrimmedInputLine = inputLine.trim();
                                  System.out.println("SocketServerThread: Input line is '" + TrimmedInputLine + "' (length: " + TrimmedInputLine.length() + ")");
                                                    /* Process the string that has been received from the client.
                                  System.out.println("SocketServerThread: input line was read");
                                                    if (TrimmedInputLine.equalsIgnoreCase("bye")){
                                       running = false;
                        else{
                                  // set the status of this thread so that it closes the connection and exits.                              
                                  running = false;
                        inputLine = null;
                                    yield();
                            in.close();
                            System.out.println("SocketServerThread: CONNECTION WITH CLIENT CLOSED");
                    } catch (IOException e) {
                            e.printStackTrace();

    Sounds like a bug to me. Do the other read() methods work as expected? I suppose you could compare the source from JDK1.3 with the source from JDK1.4 and see if something changed.
    Worst case write your own method. I had to write one for J2ME since they decided that functionality wasn't important. grr.
    Good luck.

  • Sockets hang using PrintWriter and BufferedReader

    Solaris 2.7, and Java 1.2.2
    My thread is passed a new socket = s. I then assign:
    InputStreamReader isr = new InputStreamReader(s.getInputStream());
    BufferedReader br = new BufferedReader(isr);
    PrintWriter pw = new PrintWriter(s.getOutputStream());
    The client program then sends records. If each record has only a "\r" then
    the program fails. If the client sends a "\n" or "\r\n" then the program
    works fine.
    The documentation for BufferedReader states that it looks for a "\r" or a
    "\n" or a "\r\n".
    I don't get any indication that there is a problem other than the hang.
    Upon Connect...
    Server> send("0000\n")
    client> recv("0000\n")
    client> send("0001\r")
    Server> recv("0001")
    Server> send("0002\n")
    client> recv -- nothing...
    Server> recv paused...
    I have run truss on this process and it shows that nothing is sent on the last server send above. When the client gives up (e.g. timeout) the the send completes as truss sees it.
    Is this a bug in 1.2.2. or a documentation error?

    use flush()!!

  • BufferedReader problems

    Hello all.
    I'm trying to use a BufferedReader to read in data from a file that is in a Jar. Locally of course it works but or WebStart I get java.Security.AccessControlException which leads me to believe that it is trying to read a local file and since my program is not signed, it fails. The jars will not be signed since there is no need for it given that all files will be contained withing the same jar (called: files.jar). I know that I can access this jar because I am getting all sorts of Images from it over Java WebStart. Here is my code:
         public Vector<String []> readFiletoVectorOfArrays (String delimeter, String path){
    ///unrelated code
                   System.out.println ("readFileToVectorOfArrays().path: " + path);
                   InputStream instream = getClass().getResourceAsStream(path);
                   System.out.println ("instream.toString() = " +instream.toString());
                   InputStreamReader infile = new InputStreamReader(instream);
                   System.out.println ("infile.toString = " +infile.toString());
                   BufferedReader inbuf = new BufferedReader(infile);
    // unrelated code
    }Any help is greatly appreciated.

    >
    nevermind, found the bug. >Glad you sorted it. Thanks for having the sense to report the solution back to the forum.
    >
    ..it was somewhere else completely involving JFileChoosers which of course do not work over JNLP. ...>Sure they do, as your comment above about the jars not being signed indicates you already understand. JFileChoosers work just fine for a signed app. that requests extended permissions.
    OTOH, local files can be accessed for either reading or writing even in sandboxed web start applications by using the JNLP API's FileOpenService* or FileSaveService. I had some examples up at my site, but it is offline for the moment.
    * <http://java.sun.com/j2se/1.5.0/docs/guide/javaws/jnlp/javax/jnlp/FileOpenService.html>
    An aside. I had a look at this post as soon as it first showed up. It looked to me there could be no way that code could fail in the way described, but without a complete example I did not feel confident enough to make comment.
    If you can provide an example off your server, or even a post a 'complete' example of code and JNLP file that fails for other people as it does for you - that can often speed the resolution process. I am such a fan of the complete example that I wrote an article on it, which is fortunately mirrored a number of places besides my site. Here is one mirror.. <http://homepage1.nifty.com/algafield/sscce.html>
    In this case, the process of preparing an SSCCE would hopefully have revealed the actual source of the error (by a simple process of eliminating unnecessary code).

  • BufferedReader's readLine() method problem (REPOST)

    Hello,
    If anyone can help me out I would not have to struggle :)
    Here is the thing. I have a file like this:
    1 srjetnuaazcebsqfbzerhxfbdfcbxyvihswlygzsfvjleengcftwvxcjriwdohjisnzppipiwpnniui yjpeppaezftgjfviwxunu
    2 ekjghqflatrcdteurofahxoiyvrwhvaxjgcuvkkpondsqhedxylxyjizflfbgusoizogbffgwnswohe njixwufcdlbjlkoqevqdy
    3 stfhcbslgcrywwrgbsqdkcxfbizvniyookceonscwugixgrxvvkxiqezltsiwhhepqusjdlkhadvkzg iefgarenbxnxtxnqdqpfh
    4 dcuefkdrkoovjwdrqbpgoirruutphuiobqweknxhboyktxzcczgekrlbfsbfuygjpheydiwaasxifph tldawxsfepotkgqqsivur
    5 fpfrspbuhangkeugfuwexsgivetovkoyloddgofdcajwwlrocgjrhonsrfrfxozvgohwoytycfjoycr xdhnhxyitkeqynedrbroh
    6 hgzqqsfgnotfepywbpccrosxborslqtkanyffrwknjapnzjnesjlkbbsckbyvgrxujqyocpcpctsqyz apcinhjyysxsdwfjugndr
    7 pltzealtrklzrugxdcskndqyvsrzncitqvjcnndeqossyrifzvbqovtdzsixjlizsbxwutgqipuxfid xyoktwupsuqbqgnxdfbze
    8 avpxfjgwpxnzfsfosgsryhpyaezigrqsxsgdvwdbwovhcchrijbitvbcvltrgvadogokaennwpjjpku uttidlnqftdnzqpqafels
    9 oyvztgletdwdtibshpzeuqryvulnubrqtgxwizfsdzqlgxvsebhslnovphgehfigbjyyqsirqcwflbn bnrflotpqytqzbgnkeyrk
    10 unvryrnlqucuydrasyzyiclnjvospzdoviqchdhasxzffblwsewikzbznyegrqtjvxfxfjenvrboofb xfsynlxhyuvqprqbvoruk
    and my java programs is like this:
    public String searchForAString(String fileName, int lineNumber)
    File fileObject = new File(fileName);
    String finalString ="";
    String record = "";
    int line;
    try
    FileInputStream fileInputStreamObject = new FileInputStream(fileObject);
    BufferedInputStream bufferedInputStreamObject = new BufferedInputStream(fileInputStreamObject);
    //DataInputStream dataInputStreamObject = new DataInputStream(bufferedInputStreamObject);
    BufferedReader bufferedReaderObject = new BufferedReader(new InputStreamReader(bufferedInputStreamObject));
    //System.out.println(bufferedReaderObject.readLine());
    //System.out.println("_____________________");
    while((bufferedReaderObject.readLine()) != null)
    System.out.println(bufferedReaderObject.readLine());
    Last System.out.println statement only displays second, forth, sixth, eigth, tenth and null lines. Why not every line? Any ideas? Thanks!
    Re: BufferedReader's readLine() method problem.
    Author: EagleEye101 Feb 18, 2005 8:48 PM (reply 1 of 1)
    You do relize that when you call the in.readLine() in your loop conditional and in your loop body it reads in diffrent lines. Try this:
    public String searchForAString(String fileName, int lineNumber)
    File fileObject = new File(fileName);
    String finalString ="";
    String record = "";
    int line;
    try
    FileInputStream fileInputStreamObject = new FileInputStream(fileObject);
    BufferedInputStream bufferedInputStreamObject = new BufferedInputStream(fileInputStreamObject);
    //DataInputStream dataInputStreamObject = new DataInputStream(bufferedInputStreamObject);
    BufferedReader bufferedReaderObject = new BufferedReader(new InputStreamReader(bufferedInputStreamObject));
    //System.out.println(bufferedReaderObject.readLine());
    //System.out.println("_____________________");
    String s = bufferedReaderObject.readLine();
    while(s != null)
    System.out.println(bufferedReaderObject.readLine());
    s = bufferedReaderObject.readLine();
    Every time you call the readLine method, it does read a diffrent line. Java does not know you want to read the same line twice.
    Tried it, did not work. I need to go through each line of the file I have. Any ideas?

    solution should be in your other thread.
    Please do not repeat threads--it really bugs the people here, just some 'nettiquite' --I don't mean to be a grouch.
    --later.  : )                                                                                                                                                                                                                                                                                                                                                       

  • JSP bug? url.openStream() = server redirected too many times

    I tried something the other day that works in Java, so it should work as a JSP scriptlet, but I received an error message that others have posted elsewhere without a compete resolution. Specifically, given a URL, say u, one ought to be able to do u.openStream() and eventually read the remote page. Typically, one might want to try
    URL u = new URL("http://someserver.com/path/file.xxx")
    BufferedReader bfr = new BufferedReader(new InputStreamReader(u.openStream()))and then read bfr line-by-line. The problem that seems to be fairly common is that the openStream() call throws a ProtocolException claiming "server redirected too many times (20), ."
    What I've seen is that this exception occurs whenever the URL is outside the Tomcat server whence the call is being made; in our case, we're running "out-of-the-box" Jakarta Tomcat 4.1.29 on port 8080 of a w2k server. The code works perfectly in native Java and in JSP for a URL of the form "/anotherpage.jsp"
    Is this a bug in JSP, or in our version of Tomcat, or is there just some configuration parameter that needs to be changed from its default? As I said, I've seen similar posts (with less detailed analysis) in the Usenet newsgroups, but not one has generated a response that explains and resolves the matter.
    Perhaps a JSP guru out there could set the record straight? Thanks.
    P.S. I know that the use of scriptlets in JSP is being discouraged, but they are still supported AFAIK.

    Sure scriptlets are still supported. Most times though you can do things better with a custom tag. Why reinvent the wheel?
    Just as a suggestion, you might try the JSTL <c:import> tag.
    It basically does just this behind the scenes.
    However I don't think that will help you in the end - it will probably hit the same error message.
    My guess would be that the problem is not caused by java/JSP as such, but by a firewall, or configuration somewhere.
    The following works fine for me (ignoring broken images of course)
    <%@ page import="java.net.*, java.io.*" %>
    <%
    URL u = new URL("http://www.google.com");
    BufferedReader bfr = new BufferedReader(new InputStreamReader(u.openStream()));
    String line = null;
    while ((line = bfr.readLine()) != null){
      out.println(line);
    %>Hope this helps,
    evnafets

  • Strange BufferedReader issues

    I am using bufferedreader to read a text file. When it reads the text file, there are a bunch of spaces at the end of each line, sometimes there are 2 spaces, sometimes there are 10, its completely random.
    Is there any way i can make bufferedreader.readLine(); stop at the end of the characters and not the end of the spaces? Thanks alot.

    You could trim() the string once you have read it. This will remove white space from both ends of the string.
    This assumes that the unwanted spaces are coming from the source file itself. If not, there is some bug lurking somewhere in your code because BufferedReader is known to largely avoid adding random characters to the input it returns.

  • TreeSet bug? Please take a look.

    I just got back from a programming competition. I'm very frustrated because I wrote what seems to be correct code for one of the problems, but I'm getting very strange results. After the competition I showed the code to several people and no one could figure out what's wrong with it. I'd like to know if it's a bug in Java 1.4.2_05 or my fault. Here's the problem:
    You are given a file with a list of names of songs in it. For each song you find, you must increment it's popularity, it is also case insensitive. So if you find "oh yeah" and "oH YEah", that song has a popularity of 2. Finally you must display the top five most popular songs.
    Here is the input file (songs.in):
    ACM ROX
    syzygy
    123
    thisisasong5
    myfavoritesong
    ACM ROX
    SYZYGY
    123
    thisisasong5
    ACM ROX
    sYzYgY
    123
    Acm Rox
    syzygy
    ACM ROxAnd here is my code:
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    import java.util.Comparator;
    import java.util.TreeSet;
    import java.util.Iterator;
    import java.util.NoSuchElementException;
    import java.io.BufferedReader;
    import java.io.PrintWriter;
    import java.io.InputStreamReader;
    import java.io.IOException;
    import java.io.FileReader;
    import java.io.File;
    public class Songs {
         private static final String file = "songs.in";
         TreeSet songs;
         public static void main(String[] args) {
              new Songs();
         public Songs() {
              songs = new TreeSet(new CompareSongs());
              try {
                   BufferedReader in = new BufferedReader(new FileReader(file));
                   String aSong;
                   int asdf = 0; // just for debugging; ignore this variable
                   while ((aSong = in.readLine()) != null) {
                        asdf++;
                        Iterator i = songs.iterator();
                        boolean foundSong = false;
                        while (i.hasNext()) {
                             Song song = (Song)i.next();
                             System.out.println("Loop "+asdf+": "+song.name);
                             if (song.name.equalsIgnoreCase(aSong)) {
                                  System.out.println("already have "+song.name);
                                  song.popularity++;
                                  foundSong = true;
                        if (foundSong == false) {
                             Song song1 = new Song(aSong);
                             song1.popularity++;
                             songs.add(song1);
                             System.out.println("Added song "+aSong);
                   try {
                        for (int i=0; i<5; i++) {
                             Song song2 = (Song)songs.last();
                             System.out.println(song2.name + " "+song2.popularity);
                             songs.remove(song2);
                   } catch (NoSuchElementException e) {
                        System.out.println("finish");
              } catch (IOException e) {
                   e.printStackTrace();
                   System.exit(-1);
         private class CompareSongs implements Comparator {
              public int compare(Object o1, Object o2) {
                   if (((Song)o1).popularity > ((Song)o2).popularity) {
                        return 1;
                   } else if (((Song)o1).popularity < ((Song)o2).popularity) {
                        return -1;
                   } else {
                        return 0;
         private class Song {
              public int popularity=0;
              public String name;
              public Song(String name) {
                   popularity = 0;
                   this.name = name;
              public boolean equals(Object o) {
                   if (this.name.equalsIgnoreCase(((Song)o).name))
                        return true;
                   else
                        return false;
    }The result from running this code is describe as follows: At first it will add the song to the TreeSet correctly, and the next time around it'll correctly show that there is one Song in the TreeSet. However, as more songs are added, the amount of songs returned by the Iterator remains only 1. It then says for a while that there are only two songs (when there should be a lot more), and sometimes it will actually decrease in the amount of Songs returned! (It will iterate through 3 songs, and then drop down to 1 song in the next loop around).
    Any help figuring out what's going on is greatly appreciated!

    It's not a bug in TreeSet. Lots of code uses TreeSet and works just as it should (with respect to the Set). Given a wild guess I would suppose you are modifying your Objects WHILE THEY ARE IN THE SORTED SET, thus making them unsorted and basically unfindable later. I would suggest (for a quick fix) taking the Songs out of the Tree, incrementing the popularity, and reinserting them. As a long term fix I suggest you Map names to popularities (or songs) and then finding the best ones afterward.
    ~Cheers

  • Bufferedreader class

    hi,
    im trying to use a buffered reader class to import data from a txt file and assign the data values to different data types within the application.
    however, i sometimes have the trouble that the reader gives me a null value from the reading of the first line, instead of returning what is actually there...
    the text file looks something like this
    Joe Bloggs //To be assigned to Name string within app
    123 Acre Wood //Assigned to Address 1 String within app..
    Bloggsville //Assigned to address 2 string within app
    however when i use the bufferedreader it gives me a null for reading the first line...
    This doesnt always happen and ive tried cleaning up and building the main project within netBeans several times to flush out bad code.
    i've been told that a null value means it has reached the end of the file, but how can it have done if it is the first line to be read?
    is there any way of ensuring that the first line read by the file is definately the first line of the text?
    thanks
    richard.

    Are you sure you're actually getting a null and not, say, a zero-length String?
    I've never seen this problem before and BufferedReader is so commonly used that it's hard for me to believe that such a bug exists.
    Have you written a tiny sample program that demonstrates this behavior? If so, please post it (using [code] tags).

  • Index with "or" clause (BUG still exists?)

    The change log for 2.3.10 mentions "Fixed a bug that caused incorrect query plans to be generated for predicates that used the "or" operator in conjunction with indexes [#15328]."
    But looks like the Bug still exists.
    I am listing the steps to-repro. Let me know if i have missed something (or if the bug needs to be fixed)
    DATA
    dbxml> openContainer test.dbxml
    dbxml> getDocuments
    2 documents found
    dbxml> print
    <node><value>a</value></node>
    <node><value>b</value></node>
    INDEX (just one string equality index on node "value")
    dbxml> listIndexes
    Index: unique-node-metadata-equality-string for node {http://www.sleepycat.com/2002/dbxml}:name
    Index: node-element-equality-string for node {}:value
    2 indexes found.
    QUERY
    setVerbose 2 2
    preload test.dbxml
    query 'let $temp := fn:compare("test", "test") = 0
    let $results := for $i in collection("test.dbxml")
    where ($temp or $i/node[value = ("a")])
    return $i
    return <out>{$temp}{$results}</out>'
    When $temp is true i expected the result set to contain both the records, but that was not the case with the index. It works well when there is no index!
    Result WITH INDEX
    dbxml> print
    <out>true<node><value>a</value></node></out>
    Result WITHOUT INDEX
    dbxml> print
    <out>true<node><value>a</value></node><node><value>b</value></node></out>

    Hi Vijay,
    This is a completely different bug, relating to predicate expressions that do not examine nodes. Please try the following patch, to see if it fixes this bug for you:
    --- dbxml-2.3.10-original/dbxml/src/dbxml/optimizer/QueryPlanGenerator.cpp     2007-04-18 10:05:24.000000000 +0100
    +++ dbxml-2.3.10/dbxml/src/dbxml/optimizer/QueryPlanGenerator.cpp     2007-08-08 11:32:10.000000000 +0100
    @@ -1566,11 +1572,12 @@
         else if(name == Or::name) {
              UnionQP *unionOp = new (&memMgr_) UnionQP(&memMgr_);
    +          result.operation = unionOp;
              for(VectorOfASTNodes::iterator i = args.begin(); i != args.end(); ++i) {
                   PathResult ret = generate(*i, ids);
                   unionOp->addArg(ret.operation);
    +               if(ret.operation == 0) result.operation = 0;
    -          result.operation = unionOp;
         // These operators use the presence of the node arguments, not their valueJohn

Maybe you are looking for

  • How do you put text into a photo book?

    I am new to Photoshop Elements, using Elements 11, and my first project is to make a photo book for a recent trip.  I have figured out importing the pictures and titles.  I want to include a 3000 word story on 3 or 4 pages.  I have spent hours trying

  • Web service scenario - Missing or Invalid Receiver Agreement

    Dear, We are on SAP PI 7.11 SP11 and facing a problem with a synchronous scenario SOAP <-> SAP PI <-> ABAP proxy. The Service Interfaces contain multiple operations and operation/message mappings are in place. Also, configuration on the ID side is do

  • Loader problem

    i am making a photo gallery. I load photos to a Loader by getting links from XML. My problem is this that while photos are being loaded, when next photo comes, previous one do not dissapear, can you help me to solve this problem?

  • How to see the enitre ITAB contents and down load them while debugging ?

    Hi All , One of my ITAb will be populated with 2000 records .  Is there any option in Debugging editor to download and see all the fields and all the records  at a time  instead of 5 records with few fields. We are working in ECC 6.0 . Thanks Dharma

  • My iPhone sounds as if something is loose when I tap thr back is this ok

    My iPhone sounds as if something is loose when I tap thr back is this ok