Reading Contents of File and displaying output

I'm trying to read the contents of a file, then loop through the contents, perform some formatting, and display the output. Should I read the file into an array? What is the best approach? Thanks in advance.

Depends. Is it a text file? Can you format each line independent of others? If so, you can just read one line at a time (BufferedReader) and pass it to wherever the display is. If you need to work on the file as a whole, then you need read it all at once.

Similar Messages

  • Can a servlet read a jsp file and display its contents?

    Hi,
    I would like to know if Servlets can read a Jsp file and display its contents.. Right now for our website, I am using a html file to be displayed after a successful post operation through the Servlets...
    -Thanks!

    I posted this in another thread.
    Here's some code that reads using a URL. This doesn't work with JSPs as the server executes JSP when it connects but it's useful for other file types. Note that the filename is a URI</h1>This is <code>show.jsp</code></h1>
    <hr>
    <%! String file = null; %>
    <%! java.io.InputStream is = null; %>
    <%
    file = request.getParameterValues("filename")[0];
    try {
       is = (new java.net.URL(file)).openStream();
    } catch (java.io.IOException ioe) { out.write(file + " not found!<br>"); }
    java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line = "";
    %>
    <pre>
    <%
    while((line = in.readLine()) != null) {
    %>
    <%=line%>
    <%
    %>
    </pre>

  • Reading a unicode file and displaying it on jsp !!!!!

    I've one file that consists of unicode character. I've to read it and display it on the jsp page. I'm able to display it other contents but for unicode i'm unable to display it properly. Could anyone help me how to achieve this problem.....
    in advance thanks a lot...............

    Read this.

  • Read a text file and display a xy graph

    Hi!
    I am using LabVIEW 8.5, and I am trying to read columns from
    a file and plot with xy graph. I can do it with two channels, but I am having
    problems when the numbers of channels connected increase (maybe six or ten).
    My text file looks like this:
    [Where first column x = time, the rest of the columns are
    channels = y]
    8.828        22.604        23.076            [The number of channels connected can
    change]
    9.828        22.604        22.604
    10.828      21.658        22.131
    11.828      22.131        22.131
    12.828      22.131        22.131
    13.828      22.604        22.604
    14.828      21.658        22.604
    15.828      22.131        22.131
    16.828      21.658        23.076
    17.828      22.604        22.131
    18.828      22.131        22.604
    I attached a picture of what I already try… Now I am trying
    a combination of those. If anyone has some
    advice or suggestion, please let me know.
    Sincerely,
    Julieta.
    Solved!
    Go to Solution.
    Attachments:
    xygraph.PNG ‏25 KB

    Thanks for the advice!... I just modified what I had a
    little bit and it is working, maybe is not the optimums solution…
    I would like to make the time invisible in the graph… It that possible? I attached a picture of my graph, because my English is not good.  There are two lines near to 22 (two channels
    connected at that moment), and a line near to 0 which is time (the strong pink one).  I would like to make invisible the strong
    prink one only.  I try to make invisible,
    but I fail… I changed colors looking for another solution and I fail again,
    because it is taking the colors that I choose for the channels.  I can not disable because I need it to make
    the x axes works with the time that I already saved. 
    If someone has an advice or suggestion I really appreciate it…
    Sincerely,
    Julieta.
    Attachments:
    xygraph.PNG ‏9 KB

  • Reading the XML file and displaying teh string with teh desired output

    Hi Gurus,
    I have an xml file as below.
    catalog>
    <book>
    <id>101</id>
    <genre>Computer</genre>
    <author>Jim Cortez</author>
    <title>XML for dummies</title>
    <price>44.95</price>
    <description>An in-depth look at creating mashed potatoes
    with XML.</description>
    </book>
    <book>
    <id>102</id>
    <author>George Bush</author>
    <title>I'm the decider</title>
    <genre>Fantasy</genre>
    <price>0.95</price>
    <description>I like milk and cookies.</description>
    </book>
    </catalog>
    I would like to display the Output as
    [<catalog>:1]
    [<book>:1]
    [<id>:1]
    [101:3]
    [</id>:2]
    [<genre>:1]
    [Computer:3]
    [</genre>:2]
    [<author>:1]
    [Jim Cortez:3]
    [</author>:2]
    [<title>:1]
    [XML for dummies:3]
    ............ etc., etc.,,
    here is the code template.......
    import java.io.*;
    class TagScanner implements TokenStream {
    public static final int BEGIN_TAG_TYPE = 1;
    public static final int END_TAG_TYPE = 2;
    public static final int TEXT_TYPE = 3;
    protected Reader reader = null;
    /** Lookahead char */
    protected char c;
    /** Text of currently matched token */
    protected StringBuffer text = new StringBuffer(100);
    public TagScanner(Reader reader) throws IOException {
    this.reader = reader;
    nextChar();
    protected void nextChar() throws IOException {
    c = (char)reader.read();
    public Token nextToken() throws IOException {
         if ( start of a tag ) {
         // scarf until end of tag
         // type is either BEGIN_TAG_TYPE or END_TAG_TYPE
         if ( end of file ) {
         type = Token.EOF_TYPE;
         text = "end-of-file";
         else {
         // scarf until start of a tag
         type = TEXT_TYPE;
         if ( just whitespace ) {
         // ignore and get another token
    return new Token(type, text.toString());
    Can someone please provide me the logic for the code please........... here is the complete link of the excersie http://www.antlr.org/wiki/display/CS652/Lexer+for+XML
    Many Thanks
    -M

    Can someone please provide me the logic for the code please..........The logic is pretty well spelled out for you in the description of the assignment and the outline for the code you provided. If you mean
    Can someone please do my homework for me....The answer to that is usually yes, someone can do your homework for you, but no, they usually won't actually do it for you.
    However, if you are really stuck on what to do, you should consider:
            if ( start of a tag ) {How would you know that you are at the start of a tag? Once you can answer that, the rest sort of works itself out as long as
                // scarf until end of tagyou realize what it means to 'scarf' and how to determine when an end-of-tag is reached (hint, very similar as to how to determine if you are at the start-of-tag).

  • Reading the XML file and displaying the string with the desired output

    Hi Gurus,
    I have an xml file as below.
    catalog>
    <book>
    <id>101</id>
    <genre>Computer</genre>
    <author>Jim Cortez</author>
    <title>XML for dummies</title>
    <price>44.95</price>
    <description>An in-depth look at creating mashed potatoes
    with XML.</description>
    </book>
    <book>
    <id>102</id>
    <author>George Bush</author>
    <title>I'm the decider</title>
    <genre>Fantasy</genre>
    <price>0.95</price>
    <description>I like milk and cookies.</description>
    </book>
    </catalog>
    I would like to display the Output as
    [<catalog>:1]
    [<book>:1]
    [<id>:1]
    [101:3]
    [</id>:2]
    [<genre>:1]
    [Computer:3]
    [</genre>:2]
    [<author>:1]
    [Jim Cortez:3]
    [</author>:2]
    [<title>:1]
    [XML for dummies:3]
    ............ etc., etc.,,
    here is the code template.......
    import java.io.*;
    class TagScanner implements TokenStream {
    public static final int BEGIN_TAG_TYPE = 1;
    public static final int END_TAG_TYPE = 2;
    public static final int TEXT_TYPE = 3;
    protected Reader reader = null;
    /** Lookahead char */
    protected char c;
    /** Text of currently matched token */
    protected StringBuffer text = new StringBuffer(100);
    public TagScanner(Reader reader) throws IOException {
    this.reader = reader;
    nextChar();
    protected void nextChar() throws IOException {
    c = (char)reader.read();
    public Token nextToken() throws IOException {
    if ( start of a tag ) {
    // scarf until end of tag
    // type is either BEGIN_TAG_TYPE or END_TAG_TYPE
    if ( end of file ) {
    type = Token.EOF_TYPE;
    text = "end-of-file";
    else {
    // scarf until start of a tag
    type = TEXT_TYPE;
    if ( just whitespace ) {
    // ignore and get another token
    return new Token(type, text.toString());
    Can someone please provide me the logic for the code please........... here is the complete link of the excersie
    http://www.antlr.org/wiki/display/CS652/Lexer+for+XML
    Many Thanks
    -M

    Can someone please provide me the logic for the code please..........The logic is pretty well spelled out for you in the description of the assignment and the outline for the code you provided. If you mean
    Can someone please do my homework for me....The answer to that is usually yes, someone can do your homework for you, but no, they usually won't actually do it for you.
    However, if you are really stuck on what to do, you should consider:
            if ( start of a tag ) {How would you know that you are at the start of a tag? Once you can answer that, the rest sort of works itself out as long as
                // scarf until end of tagyou realize what it means to 'scarf' and how to determine when an end-of-tag is reached (hint, very similar as to how to determine if you are at the start-of-tag).

  • How to read a text file and only output every other line?

    I am just writing a program that reads a file but outputs only every other line. Any ideas...please? thanks

    I'd start with something like this and expand on it as you go:
    File file = <whatever>;
    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader(file));
        int i = -1;
        for (String line = null; (line = in.readLine()) != null; ) {
            if ((++i % 2) == 0) {
                System.out.println(line);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
    }Shaun

  • Powershell script for pinging computers from a text file and displaying output with ip address

    i am currently using the following script to display the computers that are pinging, i also want the script to display the
    ipaddress along with the results but the results are displayed not properly, i want the result to be displayed in a table or list format, what am i missing?
    $ServerName = Get-Content "C:\scripts\computers.txt"
    foreach ($Server in $ServerName) {
    if (test-Connection -ComputerName $Server -Count 2 -Quiet) {
    "$Server is Pinging "
    } else
    {"$Server not pinging"
    foreach ($server in $servername) {
    Get-WmiObject -class "Win32_NetworkAdapterConfiguration"|Select-Object IPAddress|Format-List

    Not sure I completely understand your question but looking at the code you posted I see one fairly simple change that may be what you are missing...your Get-WMIObject statement never passes a server name to the command.  You loop through the list
    you obtained but never actually pass that to anything.  So the simple change would be to just do the following...
    foreach($server in $servername)
    Get-WMIObject -class win32_NetworkAdapterConfiguration -computername $server
    | select IPAddress | FT -auto
    you could also tuck that command into the previous foreach/if/else statement and just do each one that actually responds. 

  • Code to read xml file  and display that data using sax parser

    Hai
    My problem I have to read a xml file and display the contents of the file on console using sax parser.

    here you go

  • Reading a text file and putting it in a textarea

    hi can u tell me how to read a text file and display the contents in a text area using jsp please?
    thanks :o)

    <%@ page import="java.sql.*, java.io.*" %>
    <HTML>
    <HEAD>
         <TITLE>User Application Area</TITLE>
    <SCRIPT LANGUAGE="javascript" SRC="cal2.js">
    </SCRIPT>
    <SCRIPT LANGUAGE="javascript" SRC="cal_conf2.js"></SCRIPT>
    </HEAD>
    <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
    <%
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:fypproject","","");
    Statement st = con.createStatement();
    String email = (String)session.getAttribute("email");
    String levelStatus = (String)session.getAttribute("levelStatus");
    String details = "SELECT PD.Forename, PD.Surname, L.Level_Name FROM Personal_Details PD,
    Login_Details LD, Levels L WHERE PD.Email_Address = '" + email + "' AND PD.Email_Address =
    LD.Email_Address AND LD.Level_ID = '" + levelStatus + "' AND LD.Level_ID = L.Level_ID";
    ResultSet rsDet = st.executeQuery(details);
    if(rsDet.next()) {
    String forename = rsDet.getString("Forename");
    String surname = rsDet.getString("Surname");
    String levelName = rsDet.getString("Level_Name");
    %>
    <DIV ALIGN="center"><H1>User Application Arena</H1></DIV>
    <BR>
    <H4>Welcome back <% out.println(forename + " " + surname); %> </H4>
    <BR>
    Your status is:
    <FONT COLOR = "red">
    <% out.println(levelName); %>
    </FONT>
    <BR>
    <%
    if(levelStatus.compareTo("0")==0) {
    %>
    <BR>
    <DIV ALIGN="center">
    Please come back later and re-check your status to see if your application has progressed. If it has
    been more than a week since you submitted it please phone the HR department on 020 7123 4567
    <BR><BR>
    Log Out
    </DIV>
    </FORM>
    <%
    else if(levelStatus.compareTo("1")==0) {
    %>
    <FORM NAME="sampleform" ACTION="ProcessInterview.jsp">
    <DIV ALIGN="center">
    Congratulations, we would like to invite you for a First Round tests and interview. Please select a
    date that would suit you on our online calendar below
    <BR><BR>
    <SMALL>PLEASE CLICK HERE TO SELECT A DATE</SMALL>
    <BR><BR>
    <INPUT TYPE="text" NAME="firstinput" SIZE=20>
    <BR><BR>
    <INPUT TYPE="submit" VALUE="Confirm">
    </DIV>
    </FORM>
    <%
    else if(levelStatus.compareTo("2")==0) {
    %>
    <FORM NAME="sampleform" ACTION="ProcessInterview.jsp">
    <DIV ALIGN="center">
    Congratulations, we would like to invite you for a Second Round interview. Please select a date that
    would suit you on our online calendar below
    <BR><BR>
    <SMALL>PLEASE CLICK HERE TO SELECT A DATE</SMALL>
    <BR><BR>
    <INPUT TYPE="text" NAME="firstinput" SIZE=20>
    <BR><BR>
    <INPUT TYPE="submit" VALUE="Confirm">
    </DIV>
    </FORM>
    <%
    else if(levelStatus.compareTo("3")==0) {
    File inFile = new File("offer.txt");
    StringBuffer sb = new StringBuffer();
    BufferedReader buf = new BufferedReader(new FileReader(inFile));
    while (buf.ready()) {       
    sb.append(buf.readLine());
    buf.close();
    %>
    <TEXTAREA NAME ="text" ROWS="10" COLS="60">
    <%= sb.toString() %>
    </TEXTAREA>
    <%
    else if(levelStatus.compareTo("4")==0) {
    out.println("send rej email");
    st.close();
    con.close();
    %>
    </BODY>
    </HTML>
    THANKS!! :o)

  • Hi i am new to labview. i want to extract data from a text file and display it on the front panel. how do i proceed??

    Hi i am new to labview
    I want to extract data from a text file and display it on the front panel.
    How do i proceed??
    I have attached a file for your brief idea...
    Attachments:
    extract.jpg ‏3797 KB

    RoopeshV wrote:
    Hi,
    The below code shows how to read from txt file and display in the perticular fields.
    Why have you used waveform?
    Regards,
    Roopesh
    There are so many things wrong with this VI, I'm not even sure where to start.
    Hard-coding paths that point to your user folder on the block diagram. What if somebody else tries to run it? They'll get an error. What if somebody tries to run this on Windows 7? They'll get an error. What if somebody tries to run this on a Mac or Linux? They'll get an error.
    Not using Read From Spreadsheet File.
    Use of local variables to populate an array.
    Cannot insert values into an empty array.
    What if there's a line missing from the text file? Now your data will not line up. Your case structure does handle this.
    Also, how does this answer the poster's question?

  • // Code Help need .. in Reading CSV file and display the Output.

    Hi All,
    I am a new Bee in code and started learning code, I have stared with Console application and need your advice and suggestion.
    I want to write a code which read the input from the CSV file and display the output in console application combination of first name and lastname append with the name of the collage in village
    The example of CSV file is 
    Firstname,LastName
    Happy,Coding
    Learn,C#
    I want to display the output as
    HappyCodingXYZCollage
    LearnC#XYXCollage
    The below is the code I have tried so far.
     // .Reading a CSV
                var reader = new StreamReader(File.OpenRead(@"D:\Users\RajaVill\Desktop\C#\input.csv"));
                List<string> listA = new List<string>();
                            while (!reader.EndOfStream)
                    var line = reader.ReadLine();
                    string[] values = line.Split(',');
                    listA.Add(values[0]);
                    listA.Add(values[1]);
                    listA.Add(values[2]);          
                    // listB.Add(values[1]);
                foreach (string str in listA)
                    //StreamWriter writer = new StreamWriter(File.OpenWrite(@"D:\\suman.txt"));
                    Console.WriteLine("the value is {0}", str);
                    Console.ReadLine();
    Kindly advice and let me know, How to read the column header of the CSV file. so I can apply my logic the display combination of firstname,lastname and name of the collage
    Best Regards,
    Raja Village Sync
    Beginer Coder

    Very simple example:
    var column1 = new List<string>();
    var column2 = new List<string>();
    using (var rd = new StreamReader("filename.csv"))
    while (!rd.EndOfStream)
    var splits = rd.ReadLine().Split(';');
    column1.Add(splits[0]);
    column2.Add(splits[1]);
    // print column1
    Console.WriteLine("Column 1:");
    foreach (var element in column1)
    Console.WriteLine(element);
    // print column2
    Console.WriteLine("Column 2:");
    foreach (var element in column2)
    Console.WriteLine(element);
    Mark as answer or vote as helpful if you find it useful | Ammar Zaied [MCP]

  • Reading from a text file and displaying the contents with in a frame

    Hi All,
    I am trying to read some data from a text file and display it on a AWT Frame. The contents of the text file are as follows:
    pcode1,pname1,price1,sname1,
    pcode2,pname2,price2,sname1,
    I am writing a method to read the contents from a text file and store them into a string by using FileInputStream and InputStreamReader.
    Now I am dividing the string(which has the contents of the text file) into tokens using the StringTokenizer class. The method is as show below
    void ReadTextFile()
                        FileInputStream fis=new FileInputStream(new File("nieman.txt"));
                         InputStreamReader isr=new InputStreamReader(fis);
                         char[] buf=new char[1024];
                         isr.read(buf,0,1024);
                         fstr=new String(buf);
                         String Tokenizer st=new StringTokenizer(fstr,",");
                         while(st.hasMoreTokens())
                                          pcode1=st.nextToken();
                               pname1=st.nextToken();
              price1=st.nextToken();
                              sname1=st.nextToken();
         } //close of while loop
                    } //close of methodHere goes my problem: I am unable to display the values of pcode1,pname1,price1,sname1 when I am trying to access them from outside the ReadTextFile method as they are storing "null" values . I want to create a persistent string variable so that I can access the contents of the string variable from anywhere with in the java file. Please provide your comments for this problem as early as possible.
    Thanks in advance.

    If pcode1,pname1,price1,sname1 are global variables, which I assume they are, then simply put the word static in front of them. That way, any class in your file can access those values by simply using this notation:
    MyClassName.pcode1;
    MyClassName.pname1;
    MyClassName.price1;
    MyClassName.sname1

  • I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?

    I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?
    Attachments:
    try2.txt ‏2 KB
    read_array.vi ‏21 KB

    The problem is in the delimiters in your text file. By default, Read From Spreadsheet File.vi expects a tab delimited file. You can specify a delimiter (like a space), but Read From Spreadsheet File.vi has a problem with repeated delimiters: if you specify a single space as a delimiter and Read From Spreadsheet File.vi finds two spaces back-to-back, it stops reading that line. Your file (as I got it from your earlier post) is delimited by 4 spaces.
    Here are some of your choices to fix your problem.
    1. Change the source file to a tab delimited file. Your VI will then run as is.
    2. Change the source file to be delimited by a single space (rather than 4), then wire a string constant containing one space to the delimiter input of Read From Spreadsheet File.vi.
    3. Wire a string constant containing 4 spaces to the delimiter input of Read From Spreadsheet File.vi. Then your text file will run as is.
    Depending on where your text file comes from (see more comments below), I'd vote for choice 1: a tab delimited text file. It's the most common text output of spreadsheet programs.
    Comments for choices 1 and 2: Where does the text file come from? Is it automatically generated or manually generated? Will it be generated multiple times or just once? If it's manually generated or generated just once, you can use any text editor to change 4 spaces to a tab or to a single space. Note: if you want to change it to a tab delimited file, you can't enter a tab directly into a box in the search & replace dialog of many programs like notepad, but you can do a cut and paste. Before you start your search and replace (just in the text window of the editor), press tab. A tab character will be entered. Press Shift-LeftArrow (not Backspace) to highlight the tab character. Press Ctrl-X to cut the tab character. Start your search and replace (Ctrl-H in notepad in Windows 2000). Click into the Find What box. Enter four spaces. Click into the Replace With box. Press Ctrl-V to paste the tab character. And another thing: older versions of notepad don't have search and replace. Use any editor or word processor that does.

  • I need to read data from a text file and display it in a datagrid.how can this be done..please help

    hey ppl
    i have a datagrid in my form.i need to read input(fields..sort of a database) from a text file and display its contents in the datagrid.
    how can this  be done.. and also after every few seconds reading event should be re executed.. and that the contents of the datagrid will keep changing as per the changes in the file...
    please help as this is urgent and important.. if possible please provide me with an example code as i am completely new to flex... 
    thanks.....  

    It's not possible to read from a file without using classes from the core API*. You'll have to get clarification from your instructor as to which classes are and are not allowed.
    [http://java.sun.com/docs/books/tutorial/essential/io/]
    *Unless you write a bunch of JNI code to replicate what the java.io classes are doing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Maybe you are looking for

  • Plan value(break up) not appearing in sales order cost report

    hi I have done sales order bom in cs61,operation in ca01,in va02 for sales order costing in itemization showing like material 100 actity      10 total 110 saved and if I see in cost report it show only revenue , cogs(110),but it is not show raw mater

  • Push notifications not working in ios 7 on iphone 5

    Since upgrading to ios 7 on my iphone 5 push notifications are not working, specifically for mail, mailbox, whatsapp and messages. I have checked all settings multiple times, hard reset and restored from back up a number of times with no results. I s

  • Insert statement is not working for z table.

    Hi experts, My insert statement is not working. I have used follwing code to update z table . INSERT ztable FROM TABLE gt_table. here i have checked gt_table and its filled up with all the records properly. now the problem is in this table i have 15

  • How do I send a picture using photoshop elements 12?

    How do I send pictures using photoshop elements 12?  I am using windows live messenger.  When I attach an adobe picture it will not send it.  It tells me it has to send it in parts.  I have never that problem until I started using the adobe 12. 

  • Logitech quickcam sphere AF

    Hi Does anyone know whether the installation software for this webcam is available for MAC OSX? The install CD says it can only be supported by Mac OS 9 (no earlier, no later versions). I have had this webcam for a while with a PC and am pretty pleas