⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 22.txt

📁 java2应用开发指南第一版
💻 TXT
字号:
例程22-1
//WriteFile.Java
import Java.awt.*;
import Java.io.*;
import Java.lang.*;
import Java.Applet.*;
public class WriteFile extends Applet 
{
    String myFile = "writetest";
    File f = new File(myFile);
    DataOutputStream dos;
  public void init() 
{
        String osname = System.getProperty("os.name");
  }
  public void paint(Graphics g) 
{
	 try 
{
  	  dos = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(myFile),128));
	  dos.writeChars("Cats can hypnotize you when you least expect it\n");
	  dos.flush();
	  g.drawString("Successfully wrote to the file ", 10, 10);
	}
	catch (SecurityException e) 
{
	  g.drawString("writeFile: caught security exception: " + e, 10, 10);
    }
	catch (IOException ioe) 
{
		g.drawString("writeFile: caught i/o exception", 10, 10);
    }
  }
}



例程22-2
// HighScorePermission.Java
import Java.security.*;
//定义安全性类
public final class HighScorePermission extends BasicPermission 
{
	//构造方法一,指定安全属性名称
    public HighScorePermission(String name)
    {
	 super(name);
    }
	//构造方法二,指定安全属性名称和安全操作
    // note that actions is ignored and not used,
    // but this constructor is still needed
    public HighScorePermission(String name, String actions) 
    {
	     super(name, actions);
    }
}



例程22-3
//HighScore.Java
import Java.io.*;
import Java.security.*;
import Java.util.Hashtable;
public class HighScore
{
    private String gameName;
    private File highScoreFile;
	 //构造方法
    public HighScore(String gameName) 
    {
	    this.gameName = gameName;
       //访问控制权限设置
	    AccessController.doPrivileged(new PrivilegedAction() 
{
	       public Object run() 
{
		      String path = System.getProperty("user.home") +
		                 File.separator + 
		                 ".highscore";
		                 highScoreFile = new File(path);
		                 return null;
	      }
	    });
    }
    //设置内容
    public void setHighScore(final int score)
	             throws IOException
    {
	   //check permission first
	   SecurityManager sm = System.getSecurityManager();
	   if (sm != null) 
{
	    sm.checkPermission(new HighScorePermission(gameName));
	   }
	   // need a doPrivileged block to manipulate the file
	   try
{
	     AccessController.doPrivileged(new PrivilegedExceptionAction() 
{
		    public Object run() throws IOException 
{
		          Hashtable scores = null;
		          // try to open the existing file. Should have a locking
		          // protocol (could use File.createNewFile).
		          try
{
			        FileInputStream fis = 
			             new FileInputStream(highScoreFile);
			        ObjectInputStream ois = new ObjectInputStream(fis);
			        scores = (Hashtable) ois.readObject();
		         }
catch (Exception e) 
{
			          // ignore, try and create new file
		         }
		    // if scores is null, create a new hashtable
		    if (scores == null)
			scores = new Hashtable(13);
		    // update the score and save out the new high score
		    scores.put(gameName, new Integer(score));
		    FileOutputStream fos = new FileOutputStream(highScoreFile);
		    ObjectOutputStream oos = new ObjectOutputStream(fos);
		    oos.writeObject(scores);
		    oos.close();
		    return null;
		}
	    });
	} catch (PrivilegedActionException pae) {
	    throw (IOException) pae.getException();
	}
    }
    /**
     * get the high score. return -1 if it hasn't been set.
     *
     */
    public int getHighScore()
	throws IOException, ClassNotFoundException
    {
	//check permission first
	SecurityManager sm = System.getSecurityManager();
	if (sm != null) {
	    sm.checkPermission(new HighScorePermission(gameName));
	}
	Integer score = null;
	// need a doPrivileged block to manipulate the file
	try {
	     score = (Integer) AccessController.doPrivileged(
	                                new PrivilegedExceptionAction() {
		public Object run() 
		    throws IOException, ClassNotFoundException 
		{
		    Hashtable scores = null;
		    // try to open the existing file. Should have a locking
		    // protocol (could use File.createNewFile).
		    FileInputStream fis = 
			new FileInputStream(highScoreFile);
		    ObjectInputStream ois = new ObjectInputStream(fis);
		    scores = (Hashtable) ois.readObject();
		    // get the high score out
		    return scores.get(gameName);
		}
	    });
	} catch (PrivilegedActionException pae) {
	    Exception e = pae.getException();
	    if (e instanceof IOException)
		throw (IOException) e;
	    else
		throw (ClassNotFoundException) e;
	}
	if (score == null)
		return -1;
	else
		return score.intValue();
    }
    
    //main方法
    public static void main(String args[])
	 throws Exception 
    {
	     HighScore hs = new HighScore(args[1]);
	     if (args[0].equals("set")) 
{
	        hs.setHighScore(Integer.parseInt(args[2]));
	     }
else 
{
	         System.out.println("score = "+ hs.getHighScore());
	     }
    }
}

Java.security的文件
//
#
# This is the "master security properties file".
#
# In this file, various security properties are set for use by
# java.security classes. This is where users can statically register 
# Cryptography Package Providers ("providers" for short). The term 
# "provider" refers to a package or set of packages that supply a 
# concrete implementation of a subset of the cryptography aspects of 
# the Java Security API. A provider may, for example, implement one or 
# more digital signature algorithms or message digest algorithms.
#
# Each provider must implement a subclass of the Provider class.
# To register a provider in this master security properties file, 
# specify the Provider subclass name and priority in the format
#
#    security.provider.<n>=<className> 
#
# This declares a provider, and specifies its preference 
# order n. The preference order is the order in which providers are 
# searched for requested algorithms (when no specific provider is 
# requested). The order is 1-based; 1 is the most preferred, followed 
# by 2, and so on.
#
# <className> must specify the subclass of the Provider class whose 
# constructor sets the values of various properties that are required
# for the Java Security API to look up the algorithms or other 
# facilities implemented by the provider.
# 
# There must be at least one provider specification in java.security. 
# There is a default provider that comes standard with the JDK. It
# is called the "SUN" provider, and its Provider subclass
# named Sun appears in the sun.security.provider package. Thus, the
# "SUN" provider is registered via the following:
#
#    security.provider.1=sun.security.provider.Sun 
#
# (The number 1 is used for the default provider.) 
#
# Note: Statically registered Provider subclasses are instantiated 
# when the system is initialized. Providers can be dynamically 
# registered instead by calls to either the addProvider or 
# insertProviderAt method in the Security class.

#
# List of providers and their preference orders (see above):
#
security.provider.1=sun.security.provider.Sun

#
# Class to instantiate as the system Policy. This is the name of the class
# that will be used as the Policy object.
#
policy.provider=sun.security.provider.PolicyFile

# The default is to have a single system-wide policy file, 
# and a policy file in the user's home directory.
policy.url.1=file:${java.home}/lib/security/java.policy
policy.url.2=file:${user.home}/.java.policy

# whether or not we expand properties in the policy file
# if this is set to false, properties (${...}) will not be expanded in policy
# files.
policy.expandProperties=true

# whether or not we allow an extra policy to be passed on the command line
# with -Djava.security.policy=somefile. Comment out this line to disable
# this feature.
policy.allowSystemProperty=true

# whether or not we look into the IdentityScope for trusted Identities
# when encountering a 1.1 signed JAR file. If the identity is found
# and is trusted, we grant it AllPermission.
policy.ignoreIdentityScope=false

#
# Default keystore type.
#
keystore.type=jks

#
# Class to instantiate as the system scope:
#
system.scope=sun.security.provider.IdentityDatabase

#
# List of comma-separated packages that start with or equal this string
# will cause a security exception to be thrown when
# passed to checkPackageAccess unless the
# corresponding RuntimePermission ("accessClassInPackage."+package) has
# been granted.
package.access=sun.

#
# List of comma-separated packages that start with or equal this string
# will cause a security exception to be thrown when
# passed to checkPackageDefinition unless the
# corresponding RuntimePermission ("defineClassInPackage."+package) has
# been granted.
# 
# by default, no packages are restricted for definition, and none of
# the class loaders supplied with the JDK call checkPackageDefinition.
#
#package.definition=

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -