?
Solved

how to read file with a java applet.

Posted on 2003-03-04
15
Medium Priority
?
309 Views
Last Modified: 2013-12-29
okay. here's my question:
I've got this applet. it's supposed to read in a text file on the server (the same server on which it resides, in the same folder and all) and draw a chart from the information it gets from the file.
I don't want to read files on the client's machine or whatever. I just want to read files on the server.

the applet works fine in the applet viewer, but on the web it doesn't.

I've read about security policies and permissions. and I've also checked with the servlets... but I want to know if there's another way of reading files... without servlets or security permissions or signing the applet.
they all seem to be for applets that either have to read/write on the client's machine or for applets that have to collect information from the client's machine.

so.
I don't have to read/write on the client's machine.
the applet ONLY has to read in the file in order to draw the chart.

now, can someone tell me if it's possible to do this? and possibly... how to do this?

(I'm using Visual Age for Java 3.5 to code the applet and I have Java Sun's platform 1.4.1 as a runtime engine)

arigatou...

0
Comment
Question by:supaida
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
  • 3
15 Comments
 
LVL 1

Expert Comment

by:sct75
ID: 8067297
Good news is that it is doable. :) Instead of referencing the applet class directly in your html page, you need to jar your applet classes together with your file into a single jar file and refer the jar file as codebase in your HTML file. Following is a dummy example that you might consider to follow, say the jar file is named "applet.jar".

<APPLET CODE = "yourapplet.class" CODEBASE = "." ARCHIVE = "applet.jar" WIDTH = "600" HEIGHT = "500" >
<PARAM ... > <!-- The list of params you might have -->
</APPLET>

And in your applet code, you just refer to the file by its name, since it is already in the jar.
0
 
LVL 1

Expert Comment

by:hdane
ID: 8070505
The problem is that the applets are running on the client side, and the file resides on the server. And you are probably refrencing the file using local path to it. Try using global path to fetch the file.
If you use the solution proposed by sct75, you will unnecessary increase the amount of data sending to the client (if the file is needed in any scenario, it's OK).
0
 

Author Comment

by:supaida
ID: 8072461
to sct75: your solution would've worked great, but I forgot to mention that the files change regularly and I can't include them in the .jar file. ^^;

to hdane: I figured as much... but I didn't know about the 'global path' thing.
now could you give me an example of a 'global path', please?

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Expert Comment

by:hdane
ID: 8072713
If your file is placed on dir/file.txt (local path), global path for it will be serv/dir/file.txt, where serv is server's name/IP.
0
 
LVL 1

Expert Comment

by:sct75
ID: 8074014
If your web server is configured securely or the file is not publicly accessible to everyone who knows its IP address, you might not be able to access the file on the server directly by using sev/dir/file.txt.

Instead, you might consider create a Servlet and let your Applet talk to the servlet to obtain the file info. If you need help on how to communicate between Servlet and Applet, please let me know and I could post the solution later.
0
 
LVL 1

Expert Comment

by:sct75
ID: 8074534
If your web server is configured securely or the file is not publicly accessible to everyone who knows its IP address, you might not be able to access the file on the server directly by using sev/dir/file.txt.

Instead, you might consider create a Servlet and let your Applet talk to the servlet to obtain the file info. If you need help on how to communicate between Servlet and Applet, please let me know and I could post the solution later.
0
 
LVL 1

Expert Comment

by:hdane
ID: 8075888
Sure, security always makes life harder.
0
 

Author Comment

by:supaida
ID: 8088890
okay. *sigh* the sever is, obviously (couldn't be easy, now could it?), very secure. so I can't use the global path.
I'll use the servlet ^^; but I still don't know how to use those... so, any example would be good.

and just so you know... I won't be coming back here 'till next tuesday... at least, I won't be able to test you're suggestions until next tuesday... so take your time! ^_^

and thanks a whole lot, by the way!

0
 
LVL 1

Accepted Solution

by:
sct75 earned 300 total points
ID: 8111951
Following is an example code for the Applet class. Special Thanks to Marty Hall's valuable book on JSP/Servlet topic and its examples.


import java.net.*;
import java.io.*;

...

URL currentPage = getCodeBase();
// getHost returns empty string for applets from local disk.
String host = currentPage.getHost();
String resultsMessage = "Results will be shown here...";
if (host.length() == 0) {
resultsMessage = "Error: you must load this applet\n" +
                    "from a real Web server via HTTP,\n" +
                       "not from the local disk using\n" +
                       "a 'file:' URL. It is fine,\n" +
                       "however, if the Web server is\n" +
                       "running on your local system.";
//throw some exception or put your handling here...
}

//from this point on, assume the host is not empty...
String defaultURI = "/servlet/YourServlet";
String protocol = currentPage.getProtocol();
int port = -1; // I.e., default port of 80 or otherwise you specify

URL dataURL = new URL(protocol, host, port, defaultURI);
URLConnection connection = dataURL.openConnection();
     
// Make sure browser doesn't cache this URL.
connection.setUseCaches(false);
     
// Tell browser to allow me to send data to server.
connection.setDoOutput(true);
     
ByteArrayOutputStream byteStream =
new ByteArrayOutputStream(512); // Grows if necessary
// Stream that writes into buffer
PrintWriter out = new PrintWriter(byteStream, true);
String postData =
"fileName=" + URLEncoder.encode(theFileNameYouWant);
     
// Write POST data into local buffer
out.print(postData);
out.flush(); // Flush since above used print, not println

// POST requests are required to have Content-Length
String lengthString = String.valueOf(byteStream.size());
connection.setRequestProperty("Content-Length", lengthString);
     
// Netscape sets the Content-Type to multipart/form-data
// by default. So, if you want to send regular form data,
// you need to set it to
// application/x-www-form-urlencoded, which is the
// default for Internet Explorer. If you send
// serialized POST data with an ObjectOutputStream,
// the Content-Type is irrelevant, so you could
// omit this step.
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
     
// Write POST data to real output stream
byteStream.writeTo(connection.getOutputStream());

BufferedReader in =
new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line;
//assume that you want to put the content read into a list
//first.
ArrayList resultList = new ArrayList();
while((line = in.readLine()) != null) {
line = line.trim();
resultList.add(line);
}

0
 
LVL 1

Expert Comment

by:sct75
ID: 8112026
public class YourServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
//the file name parameter specified by your applet
String fileName = request.getParameter("fileName");
if(fileName==null || fileName.trim().length()==0)
{
//fileName not specified, either set to default or report error
}

//Now, fileName exists
//Following you will open the file spcified by the file name
//read it one line after the other and print each line to the output writer, using "out.println(line);". The out variable is specified already in "PrintWriter out = response.getWriter();"
0
 

Author Comment

by:supaida
ID: 8119427
kewl! arigatou!

now... just to be really sure of what I have here: those your example enable the applet to read from a file on the server or does it let it write on the server?

as I understand it, this lets you read from the file and posts whatever you read with the applet.

oh. and do I have to know the server's URL to be able to read from it? not that I can't get it... but I just want to be absolutely sure of what I'm doing before I start testing stuff. ^.^

and thanks again! this is getting a lot clearer!



0
 

Author Comment

by:supaida
ID: 8119441
man. ^^; I just realized I made a BIG typo in my post... 'those your example'... yeah right.
'does' would have been better.
sorry.
0
 
LVL 1

Expert Comment

by:sct75
ID: 8120026
In order for applet to read something from an servlet, it needs to send such request to the servlet, so definitely, it needs to know the URL of such servlet! To assign URL of servlet to the applet, you could consider:

1) hard-coded it into the applet;
2) pass it into applet by user input;
3) specify the URL as one of parameters to the applet on the HTML page u will embed the applet in.

Those lines in my post,

// Write POST data into local buffer
out.print(postData);
out.flush(); // Flush since above used print, not println

is to send a post request to the servlet. It is not applet trying to write something to the servlet.

When such request is sent, the servlet's doPost() method will be invoked. In doPost(), the servlet gets the requested file name from parameter (that is what applet puts in post request), and fetch that file, then output that file through PrintWriter out = response.getWriter(); and out.println(line);

If you wanna give a try whether such approach works, you could consider the examples that Mr. Marty Hall posted on his book site at http://archive.coreservlets.com/Chapter17.html
0
 

Author Comment

by:supaida
ID: 8121633
again: cool. I have so never heard about this stuff in school.

I'll test all this and come back later.

sorry. this is taking long.
0
 

Author Comment

by:supaida
ID: 8131010
great example. cool explanations. now I can actually code the thing!

arigatou gosaimasu! ^.^
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
This article will inform Clients about common and important expectations from the freelancers (Experts) who are looking at your Gig.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month15 days, 4 hours left to enroll

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question