Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Mar 21, 1997

Reading Text File From Server

Question:
I know I can't read files from a local machine through my browser, but I can't seem to read a file off my originating server either. There's a way to do this, right?

Is there an example of reading a text file from my server and displaying it — one that will run from a browser?

Answer:
The example below worked with Java Runner and Netscape. The main drawback is its inability to write back to the file. Unfortunately, URLs don't have associated output streams for this. To read andwrite to files on the source host, you must implement a server to which applets can send read and write requests.

import java.awt.*;
import java.applet.*;
import java.net.*;
import java.io.*;

public class Reader extends Applet {


   private TextField path;
   private ErrorFrame f = new ErrorFrame();
   URL source;
   TextArea display = new TextArea(8, 40); // 8 lines x 40 chars
   String next;
   AppletContext context;

   public void init() {
      setBackground(Color.pink);
      add(path = new TextField("", 30));
      add(new Button("HIDE FILE"));
      add(display);
      context = getAppletContext();
   }

   public boolean action(Event e, Object arg) {
      
      if (e.target == path) {
         try {
            String file = path.getText();
            source = new URL(getCodeBase(), file);
         
            DataInputStream in = new DataInputStream(source.openStream());
            // erase display
            display.setText("");
            while(null != (next = in.readLine()))
               display.appendText(next + "\n");
            in.close();
         }
         catch(IOException ioe) {
           // f.error(ioe); my error dialog
         }
      }
      else if (arg.equals("HIDE FILE")) {
            display.setText("");

         return true;
      }
      return false;
   }


} 
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date