BufferedReader's readLine() method

i use this readLine() method to read from a file.
in this file, there is only a line of normal text, say "hello".
after saving the returned String from readLine() method,
i find that it is not as same as "hello" anymore -> i get a
false while comparing the two strings : one is the derived string from bufferedreader's readLine() method, another one is from a string variable i defined in the program.
what is wrong here ?

hi ya abnormal !
below is the piece of code of mine :
=====================================               FileReader bf = new FileReader("test.txt");
               BufferedReader br = new BufferedReader(bf);
               br.readLine();
               String s1 = br.readLine();
               String s2 = "hihi";
               char[] c1 = s1.toCharArray();
               char[] c2 = s2.toCharArray();
               System.out.println("String 1: ");
               for (int x = 0; x < c1.length; x++)
               {  System.out.print((int)c1[x]+" ");}
               System.out.println();System.out.println("String 2: ");
               for (int x = 0; x < c2.length; x++)
               {  System.out.print((int)c2[x]+" ");}
               System.out.println();               
               boolean result = false;
               if (s1 == s2)
               result=true;
               System.out.println(result);
               br.close();
               bf.close();
=============================
i get a false :(
from your piece, the output integers representing the two strings are equal. but not after the comparison...
of course , the first line in the file test.txt is "hihi".
i even tried to move the "hihi" to the 2nd line out of 3 lines in the test.txt file, to avoid EOF or \r\n , if there are... the result is the same. false ....
what could be wrong ?

Similar Messages

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

  • BufferedReader's readLine() method problem.

    Hello,
    If anyone can help me out I would not have to struggle :)
    Here is the thing. I have a file like this:
    1     srjetnuaazcebsqfbzerhxfbdfcbxyvihswlygzsfvjleengcftwvxcjriwdohjisnzppipiwpnniuiyjpeppaezftgjfviwxunu
    2     ekjghqflatrcdteurofahxoiyvrwhvaxjgcuvkkpondsqhedxylxyjizflfbgusoizogbffgwnswohenjixwufcdlbjlkoqevqdy
    3     stfhcbslgcrywwrgbsqdkcxfbizvniyookceonscwugixgrxvvkxiqezltsiwhhepqusjdlkhadvkzgiefgarenbxnxtxnqdqpfh
    4     dcuefkdrkoovjwdrqbpgoirruutphuiobqweknxhboyktxzcczgekrlbfsbfuygjpheydiwaasxifphtldawxsfepotkgqqsivur
    5     fpfrspbuhangkeugfuwexsgivetovkoyloddgofdcajwwlrocgjrhonsrfrfxozvgohwoytycfjoycrxdhnhxyitkeqynedrbroh
    6     hgzqqsfgnotfepywbpccrosxborslqtkanyffrwknjapnzjnesjlkbbsckbyvgrxujqyocpcpctsqyzapcinhjyysxsdwfjugndr
    7     pltzealtrklzrugxdcskndqyvsrzncitqvjcnndeqossyrifzvbqovtdzsixjlizsbxwutgqipuxfidxyoktwupsuqbqgnxdfbze
    8     avpxfjgwpxnzfsfosgsryhpyaezigrqsxsgdvwdbwovhcchrijbitvbcvltrgvadogokaennwpjjpkuuttidlnqftdnzqpqafels
    9     oyvztgletdwdtibshpzeuqryvulnubrqtgxwizfsdzqlgxvsebhslnovphgehfigbjyyqsirqcwflbnbnrflotpqytqzbgnkeyrk
    10     unvryrnlqucuydrasyzyiclnjvospzdoviqchdhasxzffblwsewikzbznyegrqtjvxfxfjenvrboofbxfsynlxhyuvqprqbvoruk
    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!

    You do relize that when you call the in.readLine()in
    your loop conditional and in your loop body itreads
    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 doesread
    a diffrent line. Java does not know you want toread
    the same line twice.Err, shouldn't that be:
    while(s != null)
    System.out.println(s);
    s = bufferedReaderObject.readLine();
    Otherwise, you're still discarding a line if you use
    two readLines in the while loop.yes you are correct... srry late last night and I wsa copying his code :).

  • Writing my own readLine() method

    I am trying to write my own readLine() method. I am using the read() method from BufferedReader to read one char at a time into an array. Then when I encounter a \n chacter I convert the array to a string and return it.
    The problem arrises when i reach the end of a file.
    The read() method returns a -1 when the end of the file has been reached.
    How can I get my readline method to read the last line and return it but also tell the user the end of the file has been reached?
    Thanks.

    The reason I want to write my own is beacause
    readLine() in BufferedReader has been deprecated.
    No it isn't. Not until 1.3.1, at least.
    I want to read and return lines until read() returns a
    -1. But how can i still return the last line? err... with a return statement?
    It may contain a string and then be the end of the file. How
    can I return the string and the -1?You can't. You'll have to do it the way readLine already does or really think of something new.

  • How to use the readLine()  method when reading data from a URL?

    Hello,
    I have a URL which contains text input.
    The only way to get the data from this URL is by opening a URL connection to it.
    I would like to get the data from this URL but at the same time I would like to be able to use readLine() method of BufferedReader in order to read the data line by line.
    My question is how do I combine between these two requirements in order to reed the data from the URL?
    Roy

    Hello Roy,
    can you try out this code.
      URL yahoo = new URL("http://www.yahoo.com/");
            URLConnection yc = yahoo.openConnection();
            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                    yc.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
            in.close();
    Regards,
    Mohan R

  • I need a solution for the deprecated readLine() method .

    import java.io.*;
    import java.net.*;
    class UC {
    public static void main(String args[]) throws Exception
    DataInputStream inFromUser = new DataInputStream(System.in);
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress IPAddress = InetAddress.getByName("hostname");
    byte[] sendData = new byte[1024];
    byte[] receiveData = new byte[1024];
    while(true)
    String[] sentence = inFromUser.readLine(); /* It says the readLine() method is deprecated. what is the solution for this? */
              sentence.getSubstringBytes(sentence,0, sentence.length(), sendData, 0);
    //sentence.getBytes(0, sentence.length(), sendData, 0);
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
    clientSocket.send(sendPacket);
    DatagramPacket receivePacket
    = new DatagramPacket(receiveData, receiveData.length);
    clientSocket.receive(receivePacket);
    String modifiedSentence =
    new String(receivePacket.getData());
    System.out.println("FROM SERVER:" + modifiedSentence);
         public void getSubstringBytes(String sentence,int space,int Size,byte[] sendData,int space)
                   byte[] bytes=sentence.getBytes();
                   System.arraycopy(bytes,0,sendData,0,sentence.length()-0);
    }

    Sorry, It should be the BufferedReader , not BufferedInputStream.

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

  • Make BufferedReader take \0 as end of line?

    Hi,
    I wanna make a BufferedReader's readLine() Method to take /0 as sign for end of line and not \n. Is that possible?
    Thanks
    Felix

    Since BufferedReader is a JDK class, you can't change the internal workings unless they give you a method allowing you to do so.
    Unless someone knows better, I'd say it can't be done.
    You could write your own NullTerminatedBufferedReader class. Just make it implement the java.io.Reader interface and write its methods with the behavior that you want. A bit of work, but it could be done if you know what you're doing.
    Working with null terminated strings from C/C++ or something? Why would you want to do this?
    Good luck. - MOD

  • Problem importing classes

    Hi, I've doing a simple program to read a file and output its content by using BufferedReader and readLine() methods. My executing program is "TestProgram.java" and it imports the class "InputFileReader" to use. I have all the files in the same directory C:\j2SDK1.4_0\bin.
    When I compile "TestProgram.java", it returns the error message : Cannot resolve symbol. Symbol : variable InputLineReader.
    Can someone help me with the problem? The 2 codes are provided below.
    // InputLineReader.java
    package bin;
    import java.io.*;
    import java.util.*;
    public class InputLineReader
         public static String lineRead (BufferedReader buff)
              String line = null;
              try {
              line = buff.readLine();
                   } catch(IOException e) {
              System.out.println("IO Error");
              return line;
    // TestProgram.java
    package bin;
    import java.io.*;
    import java.util.*;
    import bin.*;
    public final class TestProgram {
         public static void main (String[] args) {
              FileReader file = new FileReader ("strtestdata1.txt");
              BufferedReader buff = new BufferedReader(file);
              String output = null;
              output = InputLineReader.line;
              System.out.println(output);

    I Dont Know Exactly Why The Problem Is. .......
    Anyway here is class I have written that works ...
    It reads ffrom a while and writes to another file ..
    I hope you can get some useful info from it
    import java.io.*;
    // This class Attempts to read from a file containing text, line by line and
    // copy the contents to a new file ...................
    public class ReadAndWrite {
        // initialising variables
        private String textLine;
        int count;
        private LineNumberReader lineReader;
        private BufferedReader bReader;
        private BufferedWriter bWriter1, bWriter2;
        private File readFile, writeFile1, writeFile2;
        // constructor
        public ReadAndWrite(String pathRead, String pathWrite1, String pathWrite2) {
            try{
                readFile   = new File(pathRead);
                writeFile1 = new File(pathWrite1);
                writeFile2 = new File(pathWrite2);
                bReader    = new BufferedReader(new FileReader(readFile));
                lineReader = new LineNumberReader(bReader);
                bWriter1 = new BufferedWriter(new FileWriter(writeFile1));
                bWriter2 = new BufferedWriter(new FileWriter(writeFile2));
            }  catch (IOException e2) {
                // Catch any other IO exceptions.
                e2.printStackTrace();
        // method to read text line by line from a given file
        public String readFile()  {
            try{
                textLine = lineReader.readLine(); // reads one line and keeeps in buffer
            }  catch (FileNotFoundException e1) {
                // If this file does not exist
                System.err.println("File not found: " + readFile);
            } catch (IOException e2) {
                // Catch any other IO exceptions.
                e2.printStackTrace();
            return textLine;
        // method that writes the text to a new file line by line
        public void  writeFile(String textLine, int count1) {
            try{
                // prints the numbered text lines to the standard output
                System.out.println(count1 + "  " + textLine);
                // writes the numbered text lines to a new file
                bWriter1.write(lineReader.getLineNumber() + "  " + textLine); // text file
                bWriter1.newLine();
                bWriter2.write(lineReader.getLineNumber() + "  " + textLine); // word file
                bWriter2.newLine();
            } catch (IOException e2) {
                // Catch any other IO exceptions.
                e2.printStackTrace();
        // method calls readFile() and writeFile()
        public void process() {
            try{
                count = 1;
                // loop to call read and write methods
                // checks for text in the file = null
                do {
                    readFile();
                    if (textLine != null){
                        writeFile(textLine, count);
                        count ++;
                while (textLine != null);
                // closing all open streams when they are no longer needed
                lineReader.close();
                bWriter1.close();
                bWriter2.close();
            } catch (IOException e2) {
                // Catch any other IO exceptions.
                e2.printStackTrace();
    }

  • PrintWriter strange behaviour

    PrintWriter outputStream = new PrintWriter(new FileWriter(filenameOut));
    BufferedReader inputStream = new BufferedReader(new FileReader(filenameIn));I create a PrinterWriter like so, then I read a line of text from a text file using a BufferedReader wrapped around a FileReader. Each line of text is read by BufferedReader's readLine() method. And each line is written using the PrintWriter's println() method.
    The weird behaviour occured while running my application twice, the first iteration and second iteration output different Strings to a text file, using the same println() method of PrintWriter and each String not containing a newline character. The lengths of the two files differed, one was off by 10 lines after reading in 50 thousand lines. It took me twenty minutes to plug in flush() after every invocationg of the println() method from PrintWriter to resolve the issue. Both the PrintWriter and BufferedReader were closed after processing.
    Any possible explanations for this? I assume it's not a bug but my own personal misuse.
    Mel

    Here is an SSCCE.
    To reiterate the SSCCE below is run twice, for each run the filenameOut is changed as it can only be a non existing file (a constraint is in place). And to describe the problem in this SSCCE, there is one line that is commented/uncommeted depending on the run, refer to the body of the SSCCE for more detail.
    As you can see each run writes a different String to the file, but they both write the String on the same criteria. The String written can not be null and does not contain any new line characters. Even though both streams are closed after use, I am required to flush after each String is written to the file for both files produced in each run to have the same line count total. Otherwise if I don't flush() they differ by 10 lines. On inspection of the files, it appears one file was truncated by 10 lines at the end of the file. Approximately 50 thousand lines are processed.
    And to the replys: No exceptions are produced. Also both output filenames must be unique, they must not exist yet (again constraint in place).
    private void readThenWriteToEncodedFile(String filenameIn, String filenameOut) {
      BufferedReader inputStream = null;
      PrintWriter outputStream = null;
      try {
        inputStream = new BufferedReader(new FileReader(filenameIn));
        outputStream = new PrintWriter(new FileWriter(filenameOut));
        String line = null;
        while( (line = inputStream.readLine()) != null ) {
          String[] tokens = line.split("\t");
          if (tokens.length == 3) {
             * One of the outputStream lines below is commented out, for the two runs.
            outputStream.println(tokens[0].trim() + "\t" + tokens[1].trim() + "\t" + tokens[2].trim());  //used for first run
            //outputStream.println(tokens[tokens.length - 1].trim());  //used for second run
            outputStream.flush();  //without flushing, the files produced by the two runs differ in line size by approximately 10 lines after 50 thousand lines are processed
      } catch (IOException e) {
           e.printStackTrace();
      } finally {
        try {
          if(inputStream != null) {
            inputStream.close();
          if(outputStream != null) {
            outputStream.close();
        } catch(IOException e) {
          e.printStackTrace();
    }Mel

  • Not Sure How To Send String

    I'm totally new to trying to network using Java and extremely poor at networking in general so bear with me here.
    I'm trying to make a top down shooter and currently the application allows the user to either play as host or connect to a host but all the network communication handling I'm doing involves creating strings, sending them along the connection and interpreting the strings on their reciept.
    The problem I'm having is I keep getting an unexpected end of file exception when it tries to read in the string.
    I used a basic IM application as an example of how to connect and send info in Java, which is where I got the idea to use in.readUTF and out.writeUTF to send string information but upon looking into this problem it seems to me that read/writeUTF is not really designed for strings and there should be something else I should use instead but I'm not sure what?
    Also I'm using this to communicate point information of each player and as I understand it I should be using TCP to do this as that was what the example I'm using said it used. Though I think it might be more useful to use UDP as it's faster and it shouldn't matter if I drop a packet or two, though I'm not sure where in my code it specifies a difference between the two and if that really is the best idea.
    Here's a zip of my netbeans project, though be warned it's VERY messy, probably the messiest code I've ever written, not to mention hacky as well: http://rapidshare.com/files/369943023/KerazehDood.zip
    Any help would be great.
    Thanks.
    Edited by: ThePermster on Mar 30, 2010 6:59 AM

    Thanks that seems to make much more sense, still having some troubles though.
    Ok so now the majority of it seems to be working and it seems to be sending the String just fine. And I'm having it send the String to the BufferedWriter "out" and then using the newLine() method to send a carriage return but the BufferedReader on "in" seems to not detect the carriage return.
    I have it doing a readLine() so that (as I understand it) it should be blocking, waiting until an end of line character so I assume each call of newLine() should have it pick up something but a quick breakpoint shows that it never stops blocking on readLine().
    I assume the connection is fine because the application running as server uses the socket object returned by the accept() method.
    Is there something I've perhaps misunderstood about the BufferedReader's readLine() method?
    Here's the new version of my netbeans project:
    http://rapidshare.com/files/371224512/KerazehDood.rar
    Also on a different line of questioning, I'm just wondering about socket convention.
    I was thinking it'd be useful in a game similar to what I'm attempting to make to not only send player position information but also client keypress information, I was just wondering, if you're doing something like that would it be frowned upon to use two separate ports? I think it would make the implementation far more legible and easy to structure but wasn't sure if applications usually try to stick to only one port or not.
    Thanks.
    Edited by: ThePermster on Apr 2, 2010 10:54 AM

  • Creating Mime-messages from String data

    How do I save string data of email received from Outlook Express by calling BufferedReader's readLine() method over a socket a connection so that it can be converted into MimeMessage.

    Sorry but i didn't read your code snipppet so well.
    So you have a Vector v wicht contains the client part of the dialog.
    This is a typical conversation: ( you don't use EHLO or HELO handshake!? it's considered rude not to introduce yourself :) )
    EHLO CLIENTNAME
    250
    MAIL FROM:<[email protected]>
    250 MAIL FROM:<[email protected]> OK
    RCPT TO:<[email protected]>
    250 RCPT TO:<[email protected]> OK
    DATA
    354 Start mail input; end with <CRLF>.<CRLF>
    Message-ID: <24569170.1093420595394.JavaMail.cau@PTWPC019>
    From: [email protected]
    To: [email protected]
    Subject: something
    Mime-Version: 1.0
    Content-Type: multipart/mixed;
         boundary="----=_Part_0_17459938.1093420595224"
    ------=_Part_0_17459938.1093420595224
    Content-Type: text/plain; charset=US-ASCII
    Content-Transfer-Encoding: 7bit
    TEXT CONTENTS
    ------=_Part_0_17459938.1093420595224
    Content-Type: text/html; charset=US-ASCII
    Content-Transfer-Encoding: 7bit
    <b>HTML CONTENTS<b>
    ------=_Part_0_17459938.1093420595224--
    250 <412ADBC5000000B5> Mail accepted
    QUIT
    221 ontrob1.bmsg.nl QUIT
    The results in the vector from DATA to the ending dot . should be the part of your constructor string;
    Use this constructor
    MimeMessage mm = new MimeMessage(null,  ByteArrayInputStream( yourstring.getBytes() )  ) ;at this moment you can deconstruct the mime further.
    maybe this code will help:
    you should call the dumpPart method like this dumpPart( mm );
         Store store;
         Folder folder;
         static boolean verbose = false;
         static boolean debug = false;
         static boolean showStructure = true;
         private static void dumpPart(Part part) throws Exception {
              if (part instanceof Message)
                   dumpEnvelope((Message) part);
              /** //Dump input stream ..
              InputStream is = part.getInputStream();
              // If "is" is not already buffered, wrap a BufferedInputStream
              // around it.
              if (!(is instanceof BufferedInputStream))
                   is = new BufferedInputStream(is);
              int c;
              while ((c = is.read()) != -1)
                   System.err.write(c);
              pr("CONTENT-TYPE: " + part.getContentType());
              * Using isMimeType to determine the content type avoids
              * fetching the actual content data until we need it.
              if (part.isMimeType("text/plain")) {
                   pr("This is plain text");
                   pr("---------------------------");
                   if (!showStructure)
                        System.out.println((String) part.getContent());
              } else if (part.isMimeType("multipart/*")) {
                   pr("This is a Multipart");
                   pr("---------------------------");
                   Multipart mp = (Multipart) part.getContent();
                   level++;
                   int count = mp.getCount();
                   for (int i = 0; i < count; i++)
                        dumpPart(mp.getBodyPart(i));
                   level--;
              } else if (part.isMimeType("message/rfc822")) {
                   pr("This is a Nested Message");
                   pr("---------------------------");
                   level++;
                   dumpPart((Part) part.getContent());
                   level--;
              } else if (!showStructure) {
                   * If we actually want to see the data, and it?s not a
                   * MIME type we know, fetch it and check its Java type.
                   Object o = part.getContent();
                   if (o instanceof String) {
                        pr("This is a string");
                        pr("---------------------------");
                        System.out.println((String) o);
                   } else if (o instanceof InputStream) {
                        System.err.println("HELLO CAU 1111");
                        pr("This is just an input stream");
                        pr("---------------------------");
                        InputStream is2 = (InputStream) o;
                        int c2;
                        while ((c2= is2.read()) != -1)
                             System.out.write(c2);
                        System.err.println("\nHELLO CAU");
                   } else {
                        pr("This is an unknown type");
                        pr("---------------------------");
                        pr(o.toString());
              } else {
                   pr("This is an unknown type");
                   pr("---------------------------");
         private static void dumpEnvelope(Message msg) throws Exception {
              pr("This is the message envelope");
              pr("---------------------------");
              Address[] a;
              // FROM
              if ((a = msg.getFrom()) != null) {
                   for (int j = 0; j < a.length; j++)
                        pr("FROM: " + a[j].toString());
              //TO
              if ((a = msg.getRecipients(Message.RecipientType.TO)) != null) {
                   for (int j = 0; j < a.length; j++)
                        pr("TO: " + a[j].toString());
              // SUBJECT
              pr("SUBJECT: " + msg.getSubject());
              // DATE
              Date d = msg.getSentDate();
              pr("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));
              //FLAGS
              Flags flags = msg.getFlags();
              StringBuffer sb = new StringBuffer();
              Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
              boolean first = true;
              for (int i = 0; i < sf.length; i++) {
                   String s;
                   Flags.Flag f = sf;
                   if (f == Flags.Flag.ANSWERED)
                        s = "\\Answered";
                   else if (f == Flags.Flag.DELETED)
                        s = "\\Deleted";
                   else if (f == Flags.Flag.DRAFT)
                        s = "\\Draft";
                   else if (f == Flags.Flag.FLAGGED)
                        s = "\\Flagged";
                   else if (f == Flags.Flag.RECENT)
                        s = "\\Recent";
                   else if (f == Flags.Flag.SEEN)
                        s = "\\Seen";
                   else
                        continue; // skip it
                   if (first)
                        first = false;
                   else
                        sb.append(' ');
                   sb.append(s);
              String[] uf = flags.getUserFlags(); // get user-flag strings
              for (int i = 0; i < uf.length; i++) {
                   if (first)
                        first = false;
                   else
                        sb.append(' ');
                   sb.append(uf[i]);
              pr("FLAGS: " + sb.toString());
              // X-MAILER
              String[] hdrs = msg.getHeader("X-Mailer");
              if (hdrs != null)
                   pr("X-Mailer: " + hdrs[0]);
              else
                   pr("X-Mailer NOT available");
         static String indentStr = " ";
         static int level = 0;
         * Print a, possibly indented, string.
         public static void pr(String s) {
              if (showStructure)
                   System.out.print(indentStr.substring(0, level * 2));
              System.out.println(s);
    Tricae

  • Prob with FILE

    Hi everybody,
    I read a file txt char by char. Here is an example oy my file containt:
    INSERT INTO DBD VALUES ("aaa","aaaa","aaaa",NULL,NULL,NULL,
    TRUE,FALSE,FALSE);
    INSERT INTO SUIVI VALUES ("bbbb","bbb",NULL,NULL);
    INSERT INTO SUIVI VALUES ("cccc","ccc",NULL,NULL);
    I want ONE row of each query, my first query is not good.
    I read char by char and I place it in a BufferString. When I find a '\n' I continue without place this char in my BufferString, I place char althought i find the char ';'
    Here is my code:
    while (dejaLu < longueurFichier)
    car = (char) flotLecture.read();
    dejaLu = dejaLu + 1;
    if(car != '\n') ========>It's not good !!!
    if(car == '"') ligne.append("'");
    else ligne.append(car);
    if (car == ';')
    msg.addFenMessage(ligne.toString());
    //nbInsert = stmt.executeUpdate(ligne.toString());
    cpt++;
    ligne.delete(0, ligne.length());
    My file txt is create in DL1, I don't know the carriage return char !!!
    Please help me...

    hi,
    I think this might be a way to do it since hopefully BufferedReader's readLine method will sort out the newline problems for you
    asjf
    import java.io.*;
    import java.util.*;
    BufferedReader br = new BufferedReader(new FileReader(file));
    List lines = new ArrayList();
    String currentLine = "";
    for(String line = ""; (line=br.readLine())!=null; ){
         currentLine+=line;
         if(line.endsWith(";")){
              lines.add(currentLine);
              currentLine="";
    for(Iterator i = lines.iterator(); i.hasNext(); )
         System.out.println(i.next());

  • How to send really Chinese word, not the string "&# number " to web browser

    Each Chinese word on page sending to web browser is translated to a string in form "&#<number>" by default, it's a problem when Chinese word is included in url. How to specify sending really Chinese word, not the string "&#<number>" to web browser?

    Thanks that seems to make much more sense, still having some troubles though.
    Ok so now the majority of it seems to be working and it seems to be sending the String just fine. And I'm having it send the String to the BufferedWriter "out" and then using the newLine() method to send a carriage return but the BufferedReader on "in" seems to not detect the carriage return.
    I have it doing a readLine() so that (as I understand it) it should be blocking, waiting until an end of line character so I assume each call of newLine() should have it pick up something but a quick breakpoint shows that it never stops blocking on readLine().
    I assume the connection is fine because the application running as server uses the socket object returned by the accept() method.
    Is there something I've perhaps misunderstood about the BufferedReader's readLine() method?
    Here's the new version of my netbeans project:
    http://rapidshare.com/files/371224512/KerazehDood.rar
    Also on a different line of questioning, I'm just wondering about socket convention.
    I was thinking it'd be useful in a game similar to what I'm attempting to make to not only send player position information but also client keypress information, I was just wondering, if you're doing something like that would it be frowned upon to use two separate ports? I think it would make the implementation far more legible and easy to structure but wasn't sure if applications usually try to stick to only one port or not.
    Thanks.
    Edited by: ThePermster on Apr 2, 2010 10:54 AM

  • Input a string value

    What is the simplest method to accept an input of string value? Is buffering or string tokenizer required to perform this?

    vinayv wrote:
    What is the simplest method to accept an input of string value? Is buffering or string tokenizer required to perform this?It depends what you're doing. StringTokenizer isn't used to get an input value, it's used to separate it out into tokens. It's also deprecated in favor of String.split.
    You might want to use BufferedReader's readLine method. Or you might want to use Scanner's next, nextLine, nextInt, etc. It depends on how you're consuming and parsing input. You might even want to check out the Console class introduced in version 6.
    Start here, and play around with the above until you find what best suits your needs.
    http://java.sun.com/docs/books/tutorial/essential/io/index.html

Maybe you are looking for