Solved

StringTokenizer working on plain String text but not on String from MS Access (text = rs.getString(1);)

Posted on 2004-10-07
33
465 Views
Last Modified: 2010-03-31
Hey,

I have a problem using a string, that I have read from a MS Access-database, in a StringTokenizer. I have to user the StringTokenizer to recognize  \n so that I can put all separate lines into an array that I will later paint with a drawString()

Below is an working example where I get the text from a simple String text:

(I have declared "String text;" in my class far up in the code)

text = "this is row 1\nthis is row 2\nthis is row 3";

          StringTokenizer st = new StringTokenizer(text,"\n");
          num_lines = st.countTokens();
          lines = new String[num_lines];
          line_widths = new int[num_lines];
          for (int i = 0; i < num_lines; i++){
          lines[i] = st.nextToken();

This works like a charm and I have an array with the length of 3.


Below is the example I want to get working and that just wont work:

          try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Calling the JDBC:ODBC bridge to be able to connect to our MS Access database
            String filename = "c:/jollydb.mdb"; // declaring and setting the database-file variable
            String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="; // declaring and assigning the database driver variable
            database+= filename.trim() + ";DriverID=22;READONLY=true}";
            Connection con = DriverManager.getConnection( database ,"",""); // creating a connection object to communicate with the database via DriverManager
            Statement s = con.createStatement(); // creating a java.sql.Statement
            s.execute("SELECT news_text FROM JT_content"); // getting the our text from the database
            ResultSet rs = s.getResultSet(); // get any ResultSet that came from our query
            while ( rs.next() ) { // stepping through our data row-by-row
            text = rs.getString(1); // setting the text to be scrolled
            }
            s.close(); // closing the Statement
            con.close(); // closing the Connection
          }
          catch (Exception e) {
            System.out.println("Error: " + e);
          }

          StringTokenizer st = new StringTokenizer(text,"\n");
          num_lines = st.countTokens();
          lines = new String[num_lines];
          line_widths = new int[num_lines];
          for (int i = 0; i < num_lines; i++){
          lines[i] = st.nextToken();

The output of this will be  "this is row 1\nthis is row 2\nthis is row 3", meaning that it doesn't do **** with my "text"-string.
What am I doing wrong? I have tried to do  text.toString(); on it but it doesn't help.

Would love a quick solution.
0
Comment
Question by:mindweaver
  • 20
  • 11
33 Comments
 
LVL 37

Expert Comment

by:zzynx
ID: 12248068
Maybe try

        StringTokenizer st = new StringTokenizer(text,"[\n|\r|\n\r|\r\n]");
0
 

Author Comment

by:mindweaver
ID: 12248093
zzynx

Thanks for your quick reply, but no it had no effect.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12248099
Hey, think that should be:

    StringTokenizer st = new StringTokenizer(text,"\\n");
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12248108
And if that doesn't work:

       StringTokenizer st = new StringTokenizer(text,"[\\n|\\r|\\n\\r|\\r\\n]");
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12248147
I read for the StringTokenizer constructor with only one parameter:

Constructs a string tokenizer for the specified string.
The tokenizer uses the default delimiter set, which is " \t\n\r\f": the space character, the tab character, the newline character, the carriage-return character, and the form-feed character. Delimiter characters themselves will not be treated as tokens.

So also try:

        StringTokenizer st = new StringTokenizer(text);
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12248188
mindweaver, sorry the StringTokenizer doesn't take regular expression.
It's the String.split() that does.
So if the previous doesn't work

Try:

      String lines[] = text.split("\\n");
or
      String lines[] = text.split(""[\\n|\\r|\\n\\r|\\r\\n]");
   
0
 

Author Comment

by:mindweaver
ID: 12248193
Thanks alot!

StringTokenizer st = new StringTokenizer(text,"\\n");

worked like a charm!
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12248216
Thanks

So, with

     StringTokenizer st = new StringTokenizer(text,"\n");

you were searching for a sequence of
1) a back slash followed by
2) the character 'n'

instead of a newline.

I would really try
       String lines[] = text.split("\\n");
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12248231
That one line of code replaces all these

          StringTokenizer st = new StringTokenizer(text,"\\n");
          num_lines = st.countTokens();
          lines = new String[num_lines];
          line_widths = new int[num_lines];
          for (int i = 0; i < num_lines; i++)
             lines[i] = st.nextToken();
0
 

Author Comment

by:mindweaver
ID: 12248236
Yeah I was looking for a backslash followed by the character n.  I had manually put those \n into the text in the database field.
0
 

Author Comment

by:mindweaver
ID: 12248283
too bad I can't use that oneliner you gave me, would be nice to get rid of all that code I put in and replace it with yours.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12248321
>>too bad I can't use that oneliner you gave me
Why nt?
0
 

Author Comment

by:mindweaver
ID: 12248370
I tried it, I got no output. and isn't it looking for a "real" new line?  There are no real line breaks in the db field (don't think it's possible in ms access) it's only a text string  "this is row 1\nthis is row 2\nthis is row 3" in the db field.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12248437
>> There are no real line breaks in the db field
Oh, I see. Then you should try:

     String lines[] = text.split("\n");
0
 

Author Comment

by:mindweaver
ID: 12248540
Nope, tried it, gave me no output.

Code:

          try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Calling the JDBC:ODBC bridge to be able to connect to our MS Access database
            String filename = "c:/jollydb.mdb"; // declaring and setting the database-file variable
            String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="; // declaring and assigning the database driver variable
            database+= filename.trim() + ";DriverID=22;READONLY=true}";
            Connection con = DriverManager.getConnection( database ,"",""); // creating a connection object to communicate with the database via DriverManager
            Statement s = con.createStatement(); // creating a java.sql.Statement
            s.execute("SELECT news_text FROM JT_content"); // getting the our text from the database
            ResultSet rs = s.getResultSet(); // get any ResultSet that came from our query
            while ( rs.next() ) { // stepping through our data row-by-row
            text = rs.getString(1); // setting the text to be scrolled
            }
            s.close(); // closing the Statement
            con.close(); // closing the Connection
          }
          catch (Exception e) {
            System.out.println("Error: " + e);
          }




          String lines[] = text.split("\n");
          Font f = getFont();                     // getting our font context
          FontMetrics fm = getFontMetrics(f);     // gettomg out FontMetrics
          line_height = fm.getHeight();           // setting the line_height variable to the our font lineheight

        for (int i=0; i<num_lines; i++){          // creating a loop for drawing all of our lines
          g.drawString(lines[i], x, flexibleHeight + (i * line_height));  // drawing one line from the lines-array
        }
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 37

Expert Comment

by:zzynx
ID: 12248585
Shouldn't

      for (int i=0; i<num_lines; i++){

be

     for (int i=0; i<lines.length; i++){

?
0
 

Author Comment

by:mindweaver
ID: 12248646
Yeah :) damn have been looking at this code for 6 hours..

Thanks, still having problems though. Now I get an output but it gives the the whole string on one row :

"this is row 1\nthis is row 2\nthis is row 3"

tried both

String lines[] = text.split("\n");

and

String lines[] = text.split("\\n");

Damn, I wish I could give you more points for helping me.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12248709
Well, for me it works:

String inputString = "this is row 1\nthis is row 2\nthis is row 3";
String lines[] = inputString.split("\n");
System.out.println(lines.length);      // <<<<<< this nicely prints "3"

Could you insert that line

    System.out.println(lines.length);

in your code and tell the result?

>>Damn, I wish I could give you more points for helping me.
You're allowed to give 500 points per question.
Ask for reopening this one, incrementing the points and reaccept is an option.
;°)

0
 

Author Comment

by:mindweaver
ID: 12248761
Yeah well that's the problem :) We are back at square one.

String inputString = "this is row 1\nthis is row 2\nthis is row 3";

You got it from a nice little text-string you made static in the code.
when I do that it works for me aswell, it is when I get the exact same
string from my database that it won't recognize my "\n"'s
I have no idea why and it is really frustrating:

text = rs.getString(1); // setting the text to be scrolled

__

String inputString = "this is row 1\nthis is row 2\nthis is row 3";         (lines.length = 3)

same string but in:

text = rs.getString(1); // setting the text to be scrolled               (lines.length = 1)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12248814
Well, I would print out that "text" variable character by character (print out the ascii code) to see what Access made from that '\'+'n'
Once you know that you can pass it in split()
0
 

Author Comment

by:mindweaver
ID: 12248859
Me too if I knew how to do it :)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12248915
       String inputString = "A\nB\nC";
        for (int i=0; i<inputString.length(); i++)
            System.out.println(""+ inputString.charAt(i) + " - " +(int)inputString.charAt(i));

Prints out:

A - 65
                          // <<<<<< here the newline is printed out
 - 10                   // <<<<<< ASCII is indeed 10 (LineFeed)
B - 66

 - 10
C - 67
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12248924
Try it with putting "A\nB" in the database
0
 

Author Comment

by:mindweaver
ID: 12249120
it gave me


A - 65

\ - 92

n - 110

B - 66


Have tried to read up on how to put it into the split()-thingie but can't figure it out.
0
 
LVL 37

Accepted Solution

by:
zzynx earned 500 total points
ID: 12249280
This is how:

        String inputString = "A\\" + "nB" + "\\nC";
        String lines[] = inputString.split("\\u005cn");     // \u005c is the hex code for the backslash (92 decimal)
        System.out.println(lines.length);
        for (int i=0; i<inputString.length(); i++)
            System.out.println(""+ inputString.charAt(i) + " - " +(int)inputString.charAt(i));
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12249298
At last ;°)

If you want to reopen this question, post a zero-point question in http://www.experts-exchange.com/Community_Support/

Subject: Moderator Please Reopen
Body: Please reopen this question:
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21159428.html
0
 

Author Comment

by:mindweaver
ID: 12249367
awesome :) it worked!

thanks ALOT! :)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12249398
:)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12251801
Hi mindweaver,

ee_ai_construct tells us that this Q has been reopened.
But I didn't receive a new "Good Answer" mail, so I think it wasn't really reopened, right?
Or did I miss that mail and have you forgotten to increment the points before re-accepting?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12252467
Hi mindweaver,

Could you please make sure you
- *first* increment the points
- *then* re-accept the comment

(See the EE help pages if you don't know how to increment the points. Or ask here)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12256414
Thanks mindweaver
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now