3

I am trying to build a java applet which downloads a file to the client machine. As a java application this code worked fine but when I tried as an applet it does nothing. I have signed the .jar file and am not getting any security error messages

The Code is:

import java.io.*;
import java.net.*;
import javax.swing.*;


public class printFile extends JApplet {

public void init(){ 

try{
    java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
    java.net.URL("http://www.google.com").openStream());
    java.io.FileOutputStream fos = new java.io.FileOutputStream("google.html");
    java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
    byte data[] = new byte[1024];
    while(in.read(data,0,1024)>=0)
    {
        bout.write(data);
    }
    bout.close();
    in.close();


} catch(IOException ioe){     
}  
}
}

Can anyone help?

user1061995
  • 80
  • 3
  • 10
  • 1) `printFile` Please use common nomenclature for class/method/attribute names. 2) `java.io.BufferedInputStream` none of the fully qualified names within the `try` are needed. Use e.g. `BufferedInputStream` instead. 3) Don't swallow the `IOException`, call `ioe.printStacktrace()` 4) I understand the Google discourages direct programmatic access. Try other sites. 5) Please indent code blocks consistently. – Andrew Thompson Nov 24 '11 at 00:33

2 Answers2

4
FileOutputStream fos = new FileOutputStream("google.html");

Change that to:

File userHome = new File(System.getProperty("user.home"));
File pageOutput = new File(userHome, "google.html");
FileOutputStream fos = new FileOutputStream(pageOutput);  //see alternative below

Ideally you would put the output in either of:

  1. A sub-directory (perhaps based on the package name of the main class - to avoid collisions) of user.home. user.home is a place where the user is supposed to be able to read & create files.
  2. A path as specified by the end user with the help of a JFileChooser.
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

See this question,

Self Signed Applet Can it access Local File Systems

I believe it will help you, you need to write your code to use PrivilegedAction.

http://docs.oracle.com/javase/1.4.2/docs/api/java/security/PrivilegedAction.html

Community
  • 1
  • 1
Halfwarr
  • 7,853
  • 6
  • 33
  • 51