devxlogo

Reading Text File From Server

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 towrite back to the file. Unfortunately, URLs don’t haveassociated output streams for this. To read andwrite to fileson the source host, you must implement a serverto 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 + ”
“); in.close(); } catch(IOException ioe) { // f.error(ioe); my error dialog } } else if (arg.equals(“HIDE FILE”)) { display.setText(“”); return true; } return false; }}

See also  Digital Signage Solutions for Agile Software Development Teams
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist