read a text file from an applet

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jhardman
    Recognized Expert Specialist
    • Jan 2007
    • 3405

    read a text file from an applet

    I am having a hard time opening a text file from an applet. I remembered after an attempt or two that there were obvious security issues here, so I switched the code to pull a text file off the internet, and there is obviously some naming or reference issue that I can't get my head around. Here is my code:
    [code=java]import java.awt.*;
    import java.awt.Font;
    import java.awt.Graphi cs;
    import java.awt.FontMe trics;
    import java.io.*;
    import java.net.*;


    public class solong17 extends java.applet.App let {

    String letter = new String();

    public void paint(Graphics screen) {
    //Color bk = new Color(0,0,0);
    //Color tx = new Color(255,255,2 55);
    Font f = new Font("Arial", Font.BOLD, 18);
    FontMetrics fm = getFontMetrics( f);
    setBackground(C olor.black);
    screen.setColor (Color.white);
    screen.setFont( f);
    String s = "So long, and thanks for all the fish.";
    int x = (size().width - fm.stringWidth( s)) / 2;
    int y = size().height / 2;
    screen.drawStri ng(s, x, y);
    }

    TextArea lt;


    public void init() {

    try {
    URL page = new
    URL("http://www.worksonline .org/works/default.htm");
    }
    catch (MalformedURLEx ception e) {
    System.out.prin tln("Bad URL: http://www.worksonline .org" +
    "/works/default.htm");
    }

    URLConnection conn = null;
    InputStreamRead er in;
    BufferedReader data;
    StringBuffer buf = new StringBuffer();
    String line;
    //System.out.prin tln(page);

    try {
    conn = this.page.openC onnection(); //error is here
    conn.connect();
    in = new InputStreamRead er(conn.getInpu tStream());
    data = new BufferedReader( in);
    /*FileReader file = new FileReader("sol ong16.java");
    BufferedReader buff = new
    BufferedReader( file);
    boolean eof = false;*/
    while ((line = data.readLine() ) != null) {
    buf.append(line + "\n");
    }

    //buff.close();
    } catch (IOException e) {
    System.out.prin tln("Error -- " + e.toString());
    }

    letter = buf.toString();

    lt = new TextArea(letter , 5,50, 1);
    Color bk = new Color(10,10,25) ;
    lt.setBackgroun d(bk);
    lt.setForegroun d(Color.white);
    lt.setEditable( false);
    Font tf = new Font("Arial", Font.BOLD, 18);
    lt.setFont(tf);
    add(lt);
    }
    }[/code]The error (line 49) says "page" isn't found, so I think there is some naming or reference convention I'm missing.

    I'm just trying this task to "get my feet wet" with java. I'm heavily entrenched in Visual Basic, and really wanted something completely different, and I'm having a hard time understanding what must be some real basics.

    Jared
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Remove the "this" on line 49 where you have this.page ...

    Comment

    • jhardman
      Recognized Expert Specialist
      • Jan 2007
      • 3405

      #3
      Originally posted by r035198x
      Remove the "this" on line 49 where you have this.page ...
      Thanks for your attention, but that was one of the first things I tried and it doesn't change the error.
      Code:
      cannot find symbol
      symbol: variable page
      With the "this." the carot indicating the error location points to the dot, without it, the carot points to the p, otherwise there is no difference in the error.

      Jared

      Comment

      • BigDaddyLH
        Recognized Expert Top Contributor
        • Dec 2007
        • 1216

        #4
        Your error is here:

        [CODE=Java]try {
        URL page = new URL("...");
        }[/CODE]

        That declares page as a variable local to the try block, so it can't be used after the block. Declare it in a wider scope, for instance:

        [CODE=Java]
        URL url = null;
        try {
        page = new URL("...");
        }[/CODE]

        You shouldn't soldier on if that url is bad, though, right?

        Comment

        • jhardman
          Recognized Expert Specialist
          • Jan 2007
          • 3405

          #5
          Originally posted by BigDaddyLH
          Your error is here:
          Thanks, that did the trick. I hadn't realized that the try block had any locale.
          You shouldn't soldier on if that url is bad, though, right?
          he he. So I tried it with a URL that existed and I got an access denied exception, so back to the drawing board, but at least that's one question down. Thanks a lot.

          Jared

          Comment

          • BigDaddyLH
            Recognized Expert Top Contributor
            • Dec 2007
            • 1216

            #6
            Originally posted by jhardman
            he he. So I tried it with a URL that existed and I got an access denied exception, so back to the drawing board, but at least that's one question down. Thanks a lot.
            An untrusted applet can only open connections back on the server from which it was downloaded. This is for security. Otherwise, an applet downloaded through a firewall could try to hack into machines hidden behind the firewall.

            I'm not a fan of applets. Another option would we to write this as a normal application. Does it have to be an applet?

            Comment

            • jhardman
              Recognized Expert Specialist
              • Jan 2007
              • 3405

              #7
              Originally posted by BigDaddyLH
              An untrusted applet can only open connections back on the server from which it was downloaded. This is for security. Otherwise, an applet downloaded through a firewall could try to hack into machines hidden behind the firewall.
              I figured the problem was something like that. The applet is just hosted on my computer, I just browsed to the HTML file that displays it, I didn't use a server at all. Any hint about getting my own applet to be trusted? Or should I just put it up on the same domain as the file I was trying to download?
              Originally posted by BigDaddyLH
              I'm not a fan of applets. Another option would we to write this as a normal application. Does it have to be an applet?
              Not at all. I was trying this project to "get my feet wet" and I thought to myself, "Opening, displaying (and next step: manipulating) a text file would be a good exercize." I settled on putting it in an applet because it seemed to me that formatting and positioning are simpler there. I'm just a noob when it comes to java, and some of that stuff is still kind of confusing. In ASP I use VBScript to write the code, and HTML/CSS to do layout and formatting, and I kind of like that. Writing layout in Java seems daunting. If I were to write this as a stand-alone app, I'm not even sure what I should put it in. That's the kind of thing that makes me want to not even bother starting.

              Jared

              Comment

              • BigDaddyLH
                Recognized Expert Top Contributor
                • Dec 2007
                • 1216

                #8
                I find the opposite: it's easier to develop a GUI as a standalone application rather than as an applet. The main reason is that you don't have to fight with the browser.

                Here for example, is a standalone application that displays the contents of a URL:
                [CODE=Java]import java.io.*;
                import java.net.*;
                import javax.swing.*;

                public class TextAreaExample implements Runnable {
                public void run() {
                JTextArea textArea= new JTextArea(20, 40);
                try {
                URL url = new URL("http://java.sun.com");
                InputStream in = url.openStream( );
                textArea.read(n ew InputStreamRead er(in), url);
                } catch (IOException e) {
                throw new RuntimeExceptio n(e);
                }
                JFrame f = new JFrame("TextAre aExample");
                f.setDefaultClo seOperation(Win dowConstants.EX IT_ON_CLOSE);
                f.getContentPan e().add(new JScrollPane(tex tArea));
                f.pack();
                f.setLocationRe lativeTo(null);
                f.setVisible(tr ue);
                }

                public static void main(String[] args) throws IOException {
                SwingUtilities. invokeLater(new TextAreaExample ());
                }
                }[/CODE]
                If some of these methods are unfamiliar, why not take the Swing tutorial?

                Sun's Swing Tutorial

                Comment

                • jhardman
                  Recognized Expert Specialist
                  • Jan 2007
                  • 3405

                  #9
                  Originally posted by BigDaddyLH
                  If some of these methods are unfamiliar, why not take the Swing tutorial?

                  Sun's Swing Tutorial
                  Thanks, I'll take your advice.

                  Jared

                  Comment

                  • r035198x
                    MVP
                    • Sep 2006
                    • 13225

                    #10
                    Originally posted by jhardman
                    Thanks, I'll take your advice.

                    Jared
                    Judging from your background, I'd suggest also that you consider going the JSP way.

                    Comment

                    • jhardman
                      Recognized Expert Specialist
                      • Jan 2007
                      • 3405

                      #11
                      Originally posted by r035198x
                      Judging from your background, I'd suggest also that you consider going the JSP way.
                      I've considered, but it looks like there is more of a future in PHP or leaving scripting behind entirely. Do you do anything in JSP?

                      Jared

                      Comment

                      • Dököll
                        Recognized Expert Top Contributor
                        • Nov 2006
                        • 2379

                        #12
                        Originally posted by BigDaddyLH
                        I find the opposite: it's easier to develop a GUI as a standalone application rather than as an applet. The main reason is that you don't have to fight with the browser.

                        Here for example, is a standalone application that displays the contents of a URL:
                        [CODE=Java]import java.io.*;
                        import java.net.*;
                        import javax.swing.*;

                        public class TextAreaExample implements Runnable {
                        public void run() {
                        JTextArea textArea= new JTextArea(20, 40);
                        try {
                        URL url = new URL("http://java.sun.com");
                        InputStream in = url.openStream( );
                        textArea.read(n ew InputStreamRead er(in), url);
                        } catch (IOException e) {
                        throw new RuntimeExceptio n(e);
                        }
                        JFrame f = new JFrame("TextAre aExample");
                        f.setDefaultClo seOperation(Win dowConstants.EX IT_ON_CLOSE);
                        f.getContentPan e().add(new JScrollPane(tex tArea));
                        f.pack();
                        f.setLocationRe lativeTo(null);
                        f.setVisible(tr ue);
                        }

                        public static void main(String[] args) throws IOException {
                        SwingUtilities. invokeLater(new TextAreaExample ());
                        }
                        }[/CODE]
                        If some of these methods are unfamiliar, why not take the Swing tutorial?

                        Sun's Swing Tutorial
                        Hey, BDLH!

                        Hiya Jared...Just getting my feet wet as well, good luck:-)

                        BDLH, would you say even though a GUI as standalone app would effortlessly be converted to an Applet or otherwise work as an applet when packaged?

                        This could have come out weird, not sure the proper lingo as of yet, just trying to see what the real advantages are to building as either or.

                        Dököll

                        Comment

                        • BigDaddyLH
                          Recognized Expert Top Contributor
                          • Dec 2007
                          • 1216

                          #13
                          Originally posted by Dököll
                          Hey, BDLH!

                          BDLH, would you say even though a GUI as standalone app would effortlessly be converted to an Applet or otherwise work as an applet when packaged?
                          If you design an application with this in mind, it will be easy to wrap an applet around it. Of course, an untrusted applet can't do many things an application can do -- local file I/O, connecting to a general URL, using the system clip board, etc...

                          My main beef is that people are often told to start with applets by out-of-date textbooks and tutorials. I'll repeat what I wrote before: it's easier to develop and debug code if it's not an applet. If you really must write an applet, do the conversion as a last step.

                          Comment

                          • Dököll
                            Recognized Expert Top Contributor
                            • Nov 2006
                            • 2379

                            #14
                            Originally posted by BigDaddyLH
                            If you design an application with this in mind, it will be easy to wrap an applet around it. Of course, an untrusted applet can't do many things an application can do -- local file I/O, connecting to a general URL, using the system clip board, etc...

                            My main beef is that people are often told to start with applets by out-of-date textbooks and tutorials. I'll repeat what I wrote before: it's easier to develop and debug code if it's not an applet. If you really must write an applet, do the conversion as a last step.
                            Super appreciate it, BigDaddyLH!

                            I will keep that in mind. I actually wanted to be sure in the case I wanted persons to work on same project having each specific class in the code assigned to each specific member of the group. Take class Room, as one example, that's handled by member or person # 1, class Eat @ member # 2, and so on...

                            Sort of what one can do in any other language, like VB for instance, where one can assign modules @ 1 person each, still having the main code...

                            I think not going againts the browser therefore will help save time and effort between the group.

                            Thanks for replying on this, BigDaddyLH:-).

                            In a bit!

                            Dököll

                            Comment

                            • BigDaddyLH
                              Recognized Expert Top Contributor
                              • Dec 2007
                              • 1216

                              #15
                              Originally posted by Dököll
                              Super appreciate it, BigDaddyLH!

                              I will keep that in mind. I actually wanted to be sure in the case I wanted persons to work on same project having each specific class in the code assigned to each specific member of the group.
                              If you are working on a group project for a course, I hope your instructor started by emphasizing unit testing, first.



                              You need to be able to test your code in isolation before combining it with anyone else's. Since you've programmed in .NET you may already be familiar with NUnit, which is the /NET rewrite of the very popular Java Unit testing framework, JUnit:

                              Comment

                              Working...