Results 1 to 19 of 19

Thread: Read text file

  1. #1
    Sean04 is offline Member
    Join Date
    Jun 2010
    Posts
    8
    Rep Power
    0

    Default Read text file

    Hey!

    So I have an app that stores records to a text file. An example of one of the records in the text file is as follows:

    10/08/2010|Sean|M|7852546225|7852546225|Dr. Something

    Each field is separated by a "|".

    How can I read that text file and each record and put it in a table like this:

    App Date First Name Last Name Home Number Other Number Doctors Name
    10/08/2010 Sean M 7852546225 7852546225 Dr. Something

    I currently have this:

    Java Code:
    public synchronized static Vector readRecords(String file) throws IOException{
            Vector users = new Vector();
            BufferedReader in = new BufferedReader(
                                new FileReader(file));
            String line = in.readLine();
            while (line != null){
                StringTokenizer t = new StringTokenizer(line, "|");
                String appDate = t.nextToken();
                String firstName = t.nextToken();
                String lastName = t.nextToken();
                String homeNumber = t.nextToken();
                String otherNumber = t.nextToken();
                String doctorsName = t.nextToken();
                User user = new User(appDate, firstName, lastName, homeNumber, otherNumber, doctorsName);
                users.add(user);
                line = in.readLine();
            }
            in.close();
            return users;
        }
    And where I want the stuff to show up I have:

    Java Code:
    <%! String filename = "C:/Users/Sean/Desktop/other.txt"; %>
     <% java.util.Vector users = Booking.UserIO.readRecords("C:/Users/Sean/Desktop/other.txt");
       session.setAttribute("users", users);
     %>
    
    <table border="1" cellspacing="5" cellpadding="5">
        <tr>
            <td>Date</td>
            <th>Client First Name</th>
            <th>Client Last Name</th>
            <th>Client Phone Numbers</th>
            <th>Doctor</th>
        </tr>
    
        <tr valign="top">
            <td><p><%= pageContext.getAttribute("appDate") %></td>
            <td><p><%= pageContext.getAttribute("firstName") %></td>
            <td><p><%= pageContext.getAttribute("lastName") %></td>
            <td><p><%= pageContext.getAttribute("homeNumber") %><br><%= pageContext.getAttribute("otherNumber") %></td>
            <td><p><%= pageContext.getAttribute("doctorsName") %></td>
    
        </tr>
    
    </table>
    The only thing showing up in the table is "null".
    Hopefully theres an easier way!

    Thanks in advance,
    Sean

  2. #2
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default

    First of all, did you tokernize the content properly? Use split(), you can easily find tokens within an array.

  3. #3
    Sean04 is offline Member
    Join Date
    Jun 2010
    Posts
    8
    Rep Power
    0

    Default

    Thanks Eranga for the reply,

    To be completely honest I'm still learning about this tokernize thing. I have just gotten it from another example that was working. I tried to implement it into mine and it doesn't seem to work.

    Could you by any chance show me an example?

    Thank you Eranga!

  4. #4
    HerrK. is offline Member
    Join Date
    Jun 2010
    Location
    Berlin
    Posts
    22
    Rep Power
    0

    Default

    Hi,

    to find out whether or not your tokenizing works fine, just use some logger (or simple print the content to the commandline). If I look to the first section, I would say that everything is done correctly. BTW you could iterate over all lines more easily by using:
    Java Code:
    String line;
    while ((line = ln.readLine()) != null) {
      StringTokenizer t = new StringTokenizer(line, "|");
      ...  
      users.add(user);
    }
    In that case the value of ln.readLine() is assigned to the variable line first, and checked for null afterwards. So you don't have to call line = ln.readLine() inside the loop anymore (and you don't have to do this initialy).

    What I really miss is the check, if the expected amount of token equals the given one (files could get corrupted or wrong files could be selected). Therefore you should check the amounts (t.countTokens() will give you the current amount).
    To check if the code works correctly, just print the values of the extracted tokens to the command line System.out.println("Created user (" + appDate + " " + ... + ")");

    As I said before, I think this code should work correctly (of course the given filename must reference a valid file, which I can't proof).

    On the other side we have the JSP code, where you create a vector named users and the output by
    Java Code:
    <tr valign="top">
            <td><p><%= pageContext.getAttribute("appDate") %></td>
            <td><p><%= pageContext.getAttribute("firstName") %></td>
            <td><p><%= pageContext.getAttribute("lastName") %></td>
            <td><p><%= pageContext.getAttribute("homeNumber") %><br><%= pageContext.getAttribute("otherNumber") %></td>
            <td><p><%= pageContext.getAttribute("doctorsName") %></td>
    
        </tr>
    So I guess your problem is, that you don't ever touch the vector. In the lines <%= pageContext.getAttribute("...") %> you don't get any value out of the vector. The pageContext might not know any attribute called "appDate" and therefore return null. You should replace this by some loop. Sorry, I really haven't used JSP for a long time, so I am not sure if this works, but try something like:

    Java Code:
    <%for (User user: users) { %>
    <tr valign="top">
            <td><%= user.getAppDate() %></td>
            ....
        </tr>
    <% } %>
    assuming that the User class has a getter called getAppDate() which returns the String containing the appDate.

  5. #5
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default

    Quote Originally Posted by Sean04 View Post
    Could you by any chance show me an example?
    Sure. Go through the following code and let me know if you are stuck on it.

    Java Code:
    /* String to split. */
            String strSource = "10/08/2010|Sean|M|7852546225|7852546225|Dr. Something";
    
            /* Array to store */
            String[] strArrayObjects;
    
            /* delimiter */
            String strDelimiter = "\\|";
    
            /* given string will be split by the argument delimiter provided. */
            strArrayObjects = strSource.split(strDelimiter);
    
            /* print substrings */
            for (int i = 0; i < strArrayObjects.length; i++) {
                System.out.println(strArrayObjects[i]);
            }

  6. #6
    Sean04 is offline Member
    Join Date
    Jun 2010
    Posts
    8
    Rep Power
    0

    Default

    Thanks for the responses guys. I greatly appreciate them! I have yet to try Eranga's sample but I will get to that. I have an error that maybe one of you could assist me with. Here it is...


    Java Code:
    org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 12
    
    9: 
    10:     <%
    11: 
    12:     java.util.Vector users = Booking.UserIO.readRecords("C:/Users/Sean/Desktop/other.txt");
    13:     session.setAttribute("users", users);
    14: 
    15:     %>
    
    
    Stacktrace:
    	org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:505)
    	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:416)
    	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    	org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
    root cause
    
    java.util.NoSuchElementException
    	java.util.StringTokenizer.nextToken(StringTokenizer.java:332)
    	Booking.UserIO.readRecords(UserIO.java:34)
    	org.apache.jsp.index_jsp._jspService(index_jsp.java:65)
    	org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
    	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    	org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)

  7. #7
    Sean04 is offline Member
    Join Date
    Jun 2010
    Posts
    8
    Rep Power
    0

    Default

    ahh i fixed that problem.. I had a record that was like this "|||||"

    still shows null.... il continue working at your examples.

    Thanks!

  8. #8
    Sean04 is offline Member
    Join Date
    Jun 2010
    Posts
    8
    Rep Power
    0

    Default

    Btw Ernaga, how would I output your example in the table?

  9. #9
    Webuser is offline Senior Member
    Join Date
    Dec 2008
    Posts
    526
    Rep Power
    0

    Lightbulb

    you can simply use method split as follows

    Java Code:
    String [] a=line.split("|");
    I think that should help :)
    If my answer helped you. Please click my "REP" button and add a comment
    Have a Good Java Coding :)

  10. #10
    Sean04 is offline Member
    Join Date
    Jun 2010
    Posts
    8
    Rep Power
    0

    Default

    thanks for the reply Webuser!

    I know how to use splits in say php but im not so familiar with java... how would i go about assigning each value that is split into like appDate, firstName, lastName and so on? I'm sure its quite simple no?

  11. #11
    Webuser is offline Senior Member
    Join Date
    Dec 2008
    Posts
    526
    Rep Power
    0

    Lightbulb

    Quote Originally Posted by Sean04 View Post
    thanks for the reply Webuser!

    I know how to use splits in say php but im not so familiar with java... how would i go about assigning each value that is split into like appDate, firstName, lastName and so on? I'm sure its quite simple no?
    The code like a

    Java Code:
    String [] n=line.split("\\|");
    returns an array filled with line parts devided by "|" char. To get a table of these liness you can easly use a Vector or something more nowadays just to store the lines.

    Java Code:
    String n[];
    Vector v=new Vector();
    while(...)
    {
    
    n=line.split("\\|");
    v.addElement(Arrays.asList(n));    
    }
    and next just for your info

    Java Code:
    // Just to prove that it worked.
        Enumeration e = v.elements();
        while (e.hasMoreElements()) {
          System.out.println(e.nextElement());
        }
    Last edited by Webuser; 06-14-2010 at 05:12 AM.
    If my answer helped you. Please click my "REP" button and add a comment
    Have a Good Java Coding :)

  12. #12
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default

    Quote Originally Posted by Sean04 View Post
    Btw Ernaga, how would I output your example in the table?
    Actually it's depends on your requirements. Since each element (token) of the string individually could be accessible, and possible to format it accordingly.

  13. #13
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default

    Quote Originally Posted by Webuser View Post
    you can simply use method split as follows

    Java Code:
    String [] a=line.split("|");
    I think that should help :)
    Of course this is the way I'm using when I'm coding. I segment into several for OPs clarification, with few comments. ;)

  14. #14
    Sean04 is offline Member
    Join Date
    Jun 2010
    Posts
    8
    Rep Power
    0

    Default

    Sorry Eranga, could you show me your way to do this and maybe an example of outputting the results to an html document?

    Thanks,
    Sean

  15. #15
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    Quote Originally Posted by Sean04 View Post
    Sorry Eranga, could you show me your way to do this and maybe an example of outputting the results to an html document?

    Thanks,
    Sean
    Not compiled or tested -- read for strategy, not for absolute correctness...
    Java Code:
            public void textToHtml(String inputFileName, String outputFileName) throws IOException {
                    BufferedReader br = new BufferedReader(
                            new FileReader(new File(inputFileName)));
                    PrintWriter out = new PrintWriter(
                            new BufferedWriter(new FileWriter(outputFileName)));
                    // TODO: print all the HTML you need to that comes before the table
                    out.println("<table>");
                    out.println("<tr>");
                    out.print("<td>App Date</td>");
                    out.print("<td>First Name</td>");
                    out.print("<td>Last Name</td>");
                    out.print("<td>Home Number</td>");
                    out.print("<td>Other Number</td>");
                    out.print("<td>Doctor's Name</td>");
                    out.println("</tr>");
                    while (br.ready()) {
                            String line = br.readLine();
                            String[] a = line.split("|");
                            out.println("<tr>");
                            for (int i = 0; i < a.length; i++) {
                                    out.print("<td>" + a[i] + "</td>");
                            }
                            out.println("</tr>");
                    }
                    out.println("</table>");
                    // TODO: print any additional HTML
                    out.close();
                    br.close();
            }
    You may want to handle exceptions instead of "kicking them upstairs" and you may want your HTML formatted better.

    -Gary-

  16. #16
    Sean04 is offline Member
    Join Date
    Jun 2010
    Posts
    8
    Rep Power
    0

    Default

    Thanks for the reply! Ill give that a try. Question though... why do you have inputfilename and outputfilename. I need to read from a file?

    Thanks again,
    Sean

  17. #17
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    Quote Originally Posted by Sean04 View Post
    Thanks for the reply! Ill give that a try. Question though... why do you have inputfilename and outputfilename. I need to read from a file?

    Thanks again,
    Sean
    My example reads from a text file and writes to an HTML file. If you are doing something different, adapt the code accordingly.

    -Gary-

  18. #18
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    Quote Originally Posted by gcalvin View Post
    My example reads from a text file and writes to an HTML file. If you are doing something different, adapt the code accordingly.

    -Gary-
    After taking a better look at what you had, I think I should tell you that I'm not doing anything with JSP, so read my code just as an illustration of using .split() and then reading the resulting String[] array. Fitting that into your existing code is left to you.

    -Gary-

  19. #19
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    After looking again, I suspect that our help with .split() is a bit of a wild goose chase -- the .split() code would replace your StringTokenizer code, but it looks as if the StringTokenizer code is probably working as it should. I think your problem is a disconnect between session.setAttribute() and pageContext.getAttribute() -- I think HerrK's comment is more helpful, but I'm no JSP guru, so I don't know exactly what the answer is. Ultimately, it seems you're not actually reading from your users Vector.

    -Gary-

Similar Threads

  1. Can't read from a text file
    By kevin8160 in forum New To Java
    Replies: 2
    Last Post: 02-07-2010, 07:45 PM
  2. A more efficient way to read from a text file
    By matzahboy in forum New To Java
    Replies: 13
    Last Post: 10-14-2009, 12:35 PM
  3. Read from a text file?
    By aaronfsimons in forum New To Java
    Replies: 3
    Last Post: 05-01-2009, 05:42 AM
  4. read from text file
    By rayda in forum New To Java
    Replies: 5
    Last Post: 04-10-2009, 04:51 AM
  5. How to read a text file from a Java Archive File
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-08-2008, 10:13 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •