Affichage des articles dont le libellé est JAVA. Afficher tous les articles
Affichage des articles dont le libellé est JAVA. Afficher tous les articles

jeudi 18 octobre 2012

有关rmi 的一些问题

- the java.rmi.server.codebase Property

    the classes needed to execute remote method calls can be downloaded from "file:///" URLs, but like applets, a "file:///" URL generally requires that the client and the server reside on the SAME physical host

information from: http://docs.oracle.com/javase/1.4.2/docs/guide/rmi/codebase.html

-

mercredi 29 février 2012

[转] HashMap遍历的两种方式

第一种:
Map map = new HashMap();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry entry = (Map.Entry) iter.next();
    Object key = entry.getKey();
    Object val = entry.getValue();
}
效率高,以后一定要使用此种方式!
第二种:
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
    Object key = iter.next();
    Object val = map.get(key);
}
效率低,以后尽量少使用!

转自: http://ludaojuan21.iteye.com/blog/243475

mardi 6 décembre 2011

Use script to start/stop/restart a java program

like start tomcat, write a script to start/stop/restart a java program:

script.sh
use: sh script.sh start

#!/bin/sh 
 
SERVER=/Users/cwang/desktop/test 
cd $SERVER 
 
case "$1" in 
 
  start) 
    nohup java -Xmx128m HelloWorld > $SERVER/server.log 2>&1 & 
    echo $! > $SERVER/server.pid 
    ;; 
 
  stop) 
    kill `cat $SERVER/server.pid` 
    rm -rf $SERVER/server.pid 
    ;; 
 
  restart) 
    $0 stop 
    sleep 1 
    $0 start 
    ;; 
 
  *) 
    echo "Usage: run.sh {start|stop|restart}" 
    ;; 
 
esac 
 
exit 0



Original: http://www.iteye.com/problems/14572

jeudi 21 juillet 2011

64 bits or 32 bits?

1: how to determine the JVM that you are running is 64-bit or 32-bit?

    open the terminal and enter the following command:

    - java -d64 -version
 
    if it is a 64-bit system, you will get the following result:

        chen-macbook:~ cwang$ java -d64 -version
    Java version "1.6.0_24"
    Java(TM) SE Runtime Environment (build 1.6.0_24-b07-334-9M3326)
    Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02-334, mixed mode)


    otherwise, you will get the following result:

        chen@chen-VirtualBox:~$ java -d64 -version
    Running a 64-bit JVM is not supported on this platform.


2: how to determine your system is 64-bit or 32-bit?

    MAC OS:
        open the terminal and enter the command uname -p,
        if you get i386, that means your system is 32-bit, x86-64 otherwise.
    
 
Finished

  



 

mercredi 16 mars 2011

[转] java 追加内容到文件末尾的几种常用方法

import java.io.BufferedWriter;  
import java.io.FileOutputStream;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.io.OutputStreamWriter;  
import java.io.RandomAccessFile;  

public class WriteStreamAppend {
      /**
       * 追加文件:使用FileOutputStream,在构造FileOutputStream时,把第二个参数设为true
       *
       * @param fileName
       * @param content
       */
public static void method1(String file, String conent) {  
    BufferedWriter out = null;  
    try {  
         out = new BufferedWriter(new OutputStreamWriter(  
                  new FileOutputStream(file, true)));  
                 out.write(conent);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                out.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  

    /**
     * 追加文件:使用FileWriter
     *  
     * @param fileName
     * @param content
     */
    public static void method2(String fileName, String content) {  
        try {  
            // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(fileName, true);  
            writer.write(content);  
            writer.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  

    /**
     * 追加文件:使用RandomAccessFile
     *  
     * @param fileName
     *            文件名
     * @param content
     *            追加的内容
     */
    public static void method3(String fileName, String content) {  
        try {  
            // 打开一个随机访问文件流,按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");  
            // 文件长度,字节数
            long fileLength = randomFile.length();  
            // 将写文件指针移到文件尾。
            randomFile.seek(fileLength);  
            randomFile.writeBytes(content);  
            randomFile.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  

    public static void main(String[] args) {  
        System.out.println("start");  
        method1("c:/test.txt", "追加到文件的末尾");  
        System.out.println("end");  
    } 

原文地址:http://blog.csdn.net/jsjwk/archive/2009/02/27/3942167.aspx

mardi 15 mars 2011

how to format a double value.

public static double formatDoubleNumber (double a){
        a = Math.round(a * Math.pow(10,2));         
        a = a/Math.pow(10,2); 
        return a;       
}

lundi 14 mars 2011

Ubuntu 10.10 安装java(转)

和大多数Linux一样,一般默认安装的Open JDK,如果你只是个上网本,看看电影娱乐啥的,那肯定不用劳神了,不过如果要用JAVA来开发,还是老老实实的安装Sun JDK。还好的是,在Ubuntu 9.04以后,Sun JDK 安装已经越来越简单了。

1. 编辑 /etc/apt/sources.list

添加deb http://archive.canonical.com/ubuntu maverick partner

2. 安装JDK 


Console代码
  1. sudo apt-get update   
  2. sudo apt-get install sun-java6-jdk   

3. 可以在 /etc/jvm 查看默认的 JVM 

4. 添加环境变量

在 /etc/enviroment 中添加环境变量 :


Console代码
  1. PATH="/usr/lib/jvm/java-6-sun/bin:$PATH"  
  2. CLASSPATH="/usr/lib/jvm/java-6-sun/lib"  
  3. JAVA_HOME="/usr/lib/jvm/java-6-sun"  

顺便提一下Ubuntu10.10 里面的环境配置文件

(1)/etc/enviroment 是系统的环境变量。
(2)/etc/profile: 是所有用户的环境变量。当用户第一次登录时,该文件被执行. 并从/etc/profile.d目录的配置文件中搜集shell的设置。
(3)/etc/bashrc: 为每一个运行bash shell的用户执行此文件.当bash shell被打开时,该文件被读取。
(4)~/.bash_profile: 每个用户都可使用该文件输入专用于自己使用的shell信息,当用户登录时,该文件仅仅执行一次!默认情况下,他设置一些环境变量,执行用户的.bashrc文件。
(5)~/.bashrc: 该文件包含专用于你的bash shell的bash信息,当登录时以及每次打开新的shell时,该该文件被读取。
(6) ~/.bash_logout:当每次退出系统(退出bash shell)时,执行该文件. 另外,/etc/profile中设定的变量(全局)的可以作用于任何用户,而~/.bashrc等中设定的变量(局部)只能继承 /etc/profile中的变量,他们是"父子"关系。
(7)~/.bash_profile 是交互式、login 方式进入 bash 运行的~/.bashrc 是交互式 non-login 方式进入 bash 运行的通常二者设置大致相同,所以通常前者会调用后者。

original link: http://hi.baidu.com/insidi/blog/item/090be9d182211a289a502769.html

jeudi 21 octobre 2010

[转] Ubuntu 10.04 LTS 安装 sun-java6-jdk

今天需要用到sun的jdk,但找了半天就是找不到,只有openjdk,后来才知道,是10.04中弄走了sun-java6-jdk,官方的release notes 中看
到如下一段:

Sun Java moved to the Partner repository

For Ubuntu 10.04 LTS, the sun-java6 packages have been dropped from the Multiverse section of the Ubuntu archive. It is recommended that you use openjdk-6 instead.
If you can not switch from the proprietary Sun JDK/JRE to OpenJDK, you can install sun-java6 packages from the Canonical Partner Repository. You can configure your system to use this repository via command-line:
add-apt-repository "deb http://archive.canonical.com/ lucid partner"



于是,添加上面的源后再



sudo apt-get update



sudo apt-get install sun-java6-jdk

*原文转自:http://blog.csdn.net/cangzhubai/archive/2010/06/25/5693021.aspx

lundi 11 janvier 2010

【转】Java操作SQL数据库[查询,更新,存储过程,类型对照]

一,SQL复习

1,SQL语句分为两类:DDL(Data Definition Language)和DML(Dat Manipulation Languge,数据操作语言)。前者主要是定义数据逻辑结构,包括定义表、视图和索引;DML主要是对数据库进行查询和更新操作。

2,Create Table(DDL):

Create Table tabName(
colName1 colType1 [else],
colName2 colType2 [else],
...,
colNamen colTypen [else]
);

例如:Cteate Table pJoiner(
pno char(6) not null,
eno char(6) nut null
);

char int varchar等等都是用来定义列数据类型的保留字,其中varchar表示可变字符类型。

3,Select ,,...,
From ,,...,
[Where<条件>]

条件中的子查询:

Where Not Exists(
Select * From tab2 Where col1=col2
)//当查询结果为空时,条件为真。

4,INSERT INTO VALUES(, ...)

5,DELETE FROM [WHERE<条件>]

6,UPDATE
SET =
...
=
[WHERE<条件>]

例如:
Update exployee
Set age=27
Where name=''赵一''

二,JDBC 主要接口:

java.sql.DriverManager类用于处理驱动程序的调入并且对新的数据库连接提供支持。
java.sql.Connection,指应用程序与特定数据库的连接。
java.sql.Statement,用于一般sql语句的执行(可以是查询、更新甚至可以创建数据库的执行过程)
java.sql.ResultSet,查询所返回的结果保存在此对象中,用它可以浏览和存取数据库内的记录。

1,通过jdbc-odbc桥使用odbc数据库(并不需要jdbc Drivers)
先在odbc DSN(Data Source Name)设置处设置pubs sysDSN,sa为username,密码为空

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//加载驱动程序
con=DriverManager.getConnection("jdbc:odbc:pubs","sa","");//jdbc:odbc:pubs
con.close();
//应当catch ClassNotFoundException和SQLException
Connection的getWarning方法返回一个SQLWarning对象,在连接之前应当先检查。
使用jdbc-odbc的最大好处是:免费的。但是性能受odbc的限制,而且一般odbc驱动比较昂贵。

2,使用专门的jdbc驱动程序。//此处是mm jdbc Driver
先将jar文件放在ClassPath里面。
Class.forName("org.gjt.mm.mysql.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","root","");
con.close();

可见使用何种方式连接何种数据库与数据库的操作和连接数据库是无关的。

三,查询数据库

Statement stmt=con.createStatement();
stmt.setMaxRows()可以控制输出记录最大数量;
ResultSet rs=stmt.executeQuery("select .....");
ResultSet指向当前记录:
int userId=rs.getInt("userid");
String userName=rs.getString("username");

...或者用序号(从1开始的)

int userId=rs.getInt(1);
Stirng userName=rs.getString(2);
ClassNotFoundException是由于Class.forName()无法载入jdbc驱动程序触发的

SQLException是jdbc在执行过程中发生问题时产生。有一个额外的方法getNextException()
catch(SQLException e){
out.println(e.getMessage());
while(e=e.getNextException()){
out.println(e.getMessage());
}

}

一般来说并不建议在jsp中编写数据库的访问程序,可以将数据库的访问封装在一个javabean中。

四,ResultSet深入

1,ResultSetMetaData
ResultSet rs=stmt.executeQuery("select....");
ResultSetMetaData rsmd=rs.getMetaData(); //获取ResultSetMateData对象
int numberOfColumns=rsmd.getColumnCount();//返回列数
boolean b=rsmd.isSearchable(int i);//返回第i列是否可以用于where子句
String c=rsmd.getColumnLabel(int i);//获取第i列的列标
Objcet obj=rs.getObject();
if(obj!=null)out.println(obj.toString());
else println("");

2,SQL类型与ResultSet的getObject返回类型及对应的XXX getXXX()方法
SQL类型 JSP类型 对应的getXXX()方法
————————————————————————————————————————————
CHAR - String - String getString()
VARCHAR - String - String getString()
LONGVARCHAR - String - InputStream getAsciiStream()/getUnicodeStream()
NUMERIC - java.math.BigDecimal - java.math.BigDecimal getBigDecimal()
DECIMAL - 同上
BIT - Boolean - boolean getBoolean()
TINYINT - Integer - byte getByte()
SMALLINT - Integer - short getShort()
INTEGER - Integer - int getInt()
BIGINT - Long - long getLong()
REAL - Float - float getFloat()
FLOAT - Double - double getDouble()
DOUBLE - Double - double getDouble()
BINARY - byte[] - byte[] getBytes()
VARBINARY - byte[] - byte[] getBytes()
LONGVARBINARY - byte[] - InputStream getBinaryStream()
DATE - java.sql.Date - java.sql.Date getDate()
TIME - java.sql.Time - java.sql.Time getTime()
TIMESTAMP - java.sql.Timestamp - java.sql.Timestamp getTimestamp()

3,null
int i=rs.getInt("age");
if(!rs.wasNull())....//RecordSet::wasNull()用来检查null

4,存取大字符串和二进制文本
对于数据库中longvarchar和langvarbinary进行流操作
ResultSet rs=stmt.executeQueryString("select ...");
BufferedReader br=new BufferedReader(new InputStream(rs.getAsciiStream("vol1")));//长文本串
BufferedReader br=new BufferedReader(new InputStream(rs.getUnicodeStream("vol1")));
BufferedReader br=new BufferedReader(new InputStream(rs.getBinaryStream("vol2")));//长二进制文本
//取数据必须在rs.getAsciiStream(), rs.getUnicodeStream(), rs.getBinaryStream()等之后马上进行
五,浏览ResultSet
1,JDBC2.0提供了更多浏览ResultSet的方法
首先,确定你的jdbc驱动程序支持jdbc2.0
其次,由Connection生成Statement时要指定参数
Statement stmt=con.getStatement("游标类型", "记录更新权限");
游标类型:
ResultSet.TYPE_FORWORD_ONLY:只可以向前移动
ResultSet.TYPE_SCROLL_INSENSITIVE:可卷动。但是不受其他用户对数据库更改的影响。
ResultSet.TYPE_SCROLL_SENSITIVE:可卷动。当其他用户更改数据库时这个记录也会改变。

记录更新权限:
ResultSet.CONCUR_READ_ONLY,只读
ResultSet.CONCUR_UPDATABLE,可更新
getStatement()缺省参数:getStatement(ResultSet.TYPE_FORWORD_ONLY, ResultSet.CONCUR_READ_ONLY)

2,如果ResultSet是可卷动的,以下函数可以使用:
rs.absolute()//绝对位置,负数表示从后面数
rs.first()第一条
rs.last()最后一条
rs.previoust()前一条
rs.next()后一条
rs.beforeFirst()第一条之前
rs.afterLast()最后之后
rs.isFirst(),rs.isLast(),rs.isBeforeFirst(),rs.isAfterLast

注意,刚打开的时候是处于第一条记录之前的

六,更新数据库

1,stmt.executeUpdate("strSql"),strSql是一条sql更新语句。update,insert,delete返回影响到的条数
2,stmt.execute()方法在不知道sql语句是查询还是更新的时候用。如果产生一条以上的对象时,返回true,此时可用stmt.getResultSet()和stmt.getUpdateCount()来获取execute结果,如果不返回ResultSet对象则返回false.
3,除了Statement的executeUpdate之外还可以用ResultSet:
rs.updateInt(1,10);
rs.updateString(2,"sfafd");
rs.updateRow();

七,使用预编译PreparedStatement

PreparedStatement对象和Statement对象类似,都可以用来执行SQL语句。不同在于,数据库会对PreparedStatement的SQL语句进行预编译,而且仍旧能输入参数并重复执行编译好的查询速度比未编译的要快。
PreparedStatement stmt=con.preparedStatement("Insert Into users(userid, username) values(?,?)");
stmt.clearParameters();
stmt.setInt(1,2);
stmt.setString(2,"Big");
stmt.executeUpdate();

八,执行存储过程

1,JDBC调用存储过程,并使用存储过程的返回值。这样可以将处理工作分为服务端和客户端两部分,并大大加快系统的设计和开发的时间。比如可以重复使用服务器上的组件。使用存储过程之后大量诸计算工作可以交给数据库服务器来处理,这将降低Web服务器的负载,从而提高整个系统的性能。

2,有两个表UserMain{UserID,UserName,UserType},UserRef{BrefID, UserID, UserBrief}
下面的存储过程可以接受jdbc传来的参数,新增内容到UserMain和UserRef,并输出一个OutUserID.
CREATE PROCEDURE ap_adduser
(
@OutUserID int output, //此为输出参数,output标记
@UserName varchar(25), //参数表示方法:"@XXX"为变量名,"变量名 类型 [output]"
@UserType tinyint,
@UserBrief varchar(255),
)

AS
Declare @UserID int //定义局部变量
insert into UserMain(UserName, UserType)
values(@UserName,@UserType)
select @UserID=@@IDENTITY //赋值用select,此处自动获得ID
insert into UserRef(UserID, UserBrief)
select @OutUserID=@UserID
GO/*结束,基本结构:
CREATE PROCEDURE procedureName(
parameters
)

AS
actions
GO
*/


JSP页面中这样使用:
CallableStatement stmt=con.prepareCall("{call ap_adduser(?,?,?,?)}");
stmt.registerOutParameter(1,Types.INTEGER,1);//注册输出变量
stmt.setString(2,"edmund");
stmt.setInt(3,1);
stmt.setString(4,"description");
stmt.execute();
int userid=stmt.getInt(1);
stmt.close()

八,使用事务

1,事务中的操作是一个整体,要么都执行成功要么都不成功:事务开始后,如果所有的改变都正确,则使用commit方法将这些动作全部存入数据库,否则就使用rollback取消所有的改变动作,而这时数据库中的数据和执行事务前的是相同的。

2,使用事务时应当先用 con.setAutoCommit(false),最后使用commit或者rollback

3,rollback一般在catch段执行

九,数据库连接池

1,如果有一个数据库连接请求并且连接中没有连接,则生成一个新的连接。这个连接使用完之后并不关闭它,而是将它放入连接池。在这个过程中,还要判断连接池中的连接是否超期。如果超期则将它关闭。

2,有很多已有的Connection Pool包可以使用。

3,一般将Connection Pool作为一个application作用域的变量使用

<%@page import="java.sql.*"%>
<%@page import="javastart.tools.*"%>

DBConnection con=null;
try{
con=pool.getConnection("sun.jdbc.odbc.JdbcOdbcDriver","jdbc:odbc:access","","");
Statement stmt=con.createStatement();
stmt.setMaxRows(10);
String query=request.getParameter("quey");
ResultSet rs=stml.executeQuery(query);
ResultSetMetaData rsmd=rs.getMetaData();
}
.....
finally{
pool.releaseConnection(con);
}

也可以使用一个Servlet初始化连接池

mardi 5 janvier 2010

RMI ClassNotFoundException

RMI

多主机运行RMI 代码,遇到类似如下的错误:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: examples.callback.MessageReceiverImpl_Stub

需要把Stub 类放在Internet 能访问到的目录下!

× 需要一个安全侧略文件:
grant codeBase "file:/Users/cwang/Documents/workspace/hocl/bin/" {
permission java.security.AllPermission;
};

×显示指出哪里能找到Stub 类:
-Djava.rmi.server.codebase=file:/Users/cwang/Documents/workspace/hocl/bin/

×指明本RMI 主机HOSTNAME,如没有可用IP 代替:
-Djava.rmi.server.hostname=131.254.14.42

【转】Dynamic code downloading using RMI


Dynamic code downloading using RMI
(Using the java.rmi.server.codebase Property)



This tutorial is organized as follows:
  1. Starting out
  2. What is a codebase?
  3. How does it work?
  4. Using codebase in RMI for more than just stub downloading
  5. Command-line examples
  6. Troubleshooting tips


1.0 Starting out

One of the most significant capabilities of the JavaTM platform is the ability to dynamically download Java software from any Uniform Resource Locator (URL) to a Java virtual machine* (JVM) running in a separate process, usually on a different physical system. The result is that a remote system can run a program, for example an applet, which has never been installed on its disk. For the first few sections of this document, codebase with regard to applets will be discussed in order to help describe codebase with regard to Java Remote Method Invocation (RMI).
For example, a JVM running from within a web browser can download the bytecodes for subclasses of java.applet.Applet and any other classes needed by that applet. The system on which the browser is running has most likely never run this applet before, nor installed it on its disk. Once all the necessary classes have been downloaded from the server, the browser can start the execution of the applet program using the local resources of the system on which the client browser is running.
Java RMI takes advantage of this capability to download and execute classes and on systems where those classes have never been installed on disk. Using the RMI API any JVM, not only those in browsers, can download any Java class file including specialized RMI stub classes, which enable the execution of method calls on a remote server using the server system's resources.
The notion of a codebase originates from the use of ClassLoaders in the Java programming language. When a Java program uses a ClassLoader, that class loader needs to know the location(s) from which it should be allowed to load classes. Usually, a class loader is used in conjunction with an HTTP server that is serving up compiled classes for the Java platform. Most likely, the first ClassLoader/codebase pairing that you came into contact with was the AppletClassLoader, and the "codebase" part of the HTML tag, so this tutorial will assume that you have some experience with Java RMI programming, as well as writing HTML files that contain applet tags. For example, the HTML source will contain something like:




2.0 What is a codebase?

A codebase can be defined as a source, or a place, from which to load classes into a Java virtual machine. For example, if you invited a new friend over for dinner, you would need to give that friend directions to the place where you lived, so that he or she could locate your house. Similarly, you can think of a codebase as the directions that you give to a JVM, so it can find your [potentially remote] classes.
You can think of your CLASSPATH as a "local codebase", because it is the list of places on disk from which you load local classes. When loading classes from a local disk-based source, your CLASSPATH variable is consulted. Your CLASSPATH can be set to take either relative or absolute path names to directories and/or archives of class files. So just as CLASSPATH is a kind of "local codebase", the codebase used by applets and remote objects can be thought of as a "remote codebase".

3.0 How does it work?

3.1 How codebase is used in applets

To interact with an applet, that applet and any classes that it needs to run must be accessible by remote clients. While applets can be accessed from "ftp://" or local "file:///" URLs, they are usually accessed from a remote HTTP server.
  1. The client browser requests an applet class that is not found in the client's CLASSPATH
  2. The class definition of the applet (and any other class(es) that it needs) is downloaded from the server to the client using HTTP
  3. The applet executes on the client

illustrates three steps above Figure 1: Downloading applets

The applet's codebase is always relative to the URL of the HTML page in which the tag is contained.

3.2 How codebase is used in RMI

Using RMI, applications can create remote objects that accept method calls from clients in other JVMs. In order for a client to call methods on a remote object, the client must have a way to communicate with the remote object. Rather than having to program the client to speak the remote object's protocol, RMI uses special classes called stubs that can be downloaded to the client that are used to communicate with (make method calls on) the remote object. The java.rmi.server.codebase property value represents one or more URL locations from which these stubs (and any classes needed by the stubs) can be downloaded.
Like applets, the classes needed to execute remote method calls can be downloaded from "file:///" URLs, but like applets, a "file:///" URL generally requires that the client and the server reside on the same physical host, unless the file system referred to by the URL is made available using some other protocol, such as NFS.
Generally, the classes needed to execute remote method calls should be made accessible from a network resource, such as an HTTP or FTP server.

illustrates the first 5 steps of the stub downloadling process, as listed below Figure 2: Downloading RMI stubs

  1. The remote object's codebase is specified by the remote object's server by setting the java.rmi.server.codebase property. The RMI server registers a remote object, bound to a name, with the RMI registry. The codebase set on the server JVM is annotated to the remote object reference in the RMI registry.
  2. The RMI client requests a reference to a named remote object. The reference (the remote object's stub instance) is what the client will use to make remote method calls to the remote object.
  3. The RMI registry returns a reference (the stub instance) to the requested class. If the class definition for the stub instance can be found locally in the client's CLASSPATH , which is always searched before the codebase, the client will load the class locally. However, if the definition for the stub is not found in the client's CLASSPATH, the client will attempt to retrieve the class definition from the remote object's codebase.
  4. The client requests the class definition from the codebase. The codebase the client uses is the URL that was annotated to the stub instance when the stub class was loaded by the registry. Back in step 1, the annotated stub for the exported object was then registered with the RMI registry bound to a name.
  5. The class definition for the stub (and any other class(es) that it needs) is downloaded to the client.
  6. Note: Steps 4 and 5 are the sames steps that the registry took to load the remote object class, when the remote object was bound to a name in (registered with) the RMI registry. When the registry attempted to load the remote object's stub class, it requested the class definition from the codebase associated with that remote object.
  7. Now the client has all the information that it needs to invoke remote methods on the remote object. The stub instance acts as a proxy to the remote object that exists on the server; so unlike the applet which uses a codebase to execute code in its local JVM, the RMI client uses the remote object's codebase to execute code in another, potentially remote JVM, as illustrated in Figure 3:

illustrates the final step of the above procedure Figure 3: RMI client making a remote method call

4.0 Using codebase in RMI for more than just stub downloading

In addition to downloading stubs and their associated classes to clients, the java.rmi.server.codebase property can be used to specify a location from which any class, not only stubs, can be downloaded.
When a client makes a method call to a remote object, the method that it calls could be written to accept no arguments or a number of arguments. There are three distinct cases that may occur, based on the data type(s) of the method argument(s).
In the first case, all of the method parameters (and return value) are primitive data types, so the remote object knows how to interpret them as method parameters, and there is no need to check its CLASSPATH or any codebase.
In the second case, at least one remote method parameter or the return value is an object, for which the remote object can find the class definition locally in its CLASSPATH.
In the third case (shown as Step 6, in Figure 4), the remote method receives an object instance, for which the remote object cannot find the class definition locally in its CLASSPATH. This type of remote method call is illustrated in Figure 4. The class of the object sent by the client will be a subtype of the declared parameter type. A subtype is either:
  • An implementation of the interface that is declared as the method parameter (or return) type
  • A subclass of the class that is declared as the method parameter (or return) type

Illustrates passing an unknown  subtype as a method parameter, as described above and below. Figure 4: RMI client making a remote method call, passing an unknown subtype as a method parameter

7. Like the applet's codebase, the client-specified codebase is used to download Remote classes, non-remote classes, and interfaces to other JVMs. If the codebase property is set on the client application, then that codebase is annotated to the subtype instance when the subtype class is loaded by the client. If the codebase is not set on the client, the remote object will mistakenly use its own codebase.

5.0 Command-line examples

In the case of an applet, the applet codebase value is embedded in an HTML page, as we saw in the HTML example in the first section of this tutorial.
In the case of Java RMI codebase, rather than having a reference to the class embedded in an HTML page, the client first contacts the RMI registry for a reference to the remote object. Because the remote object's codebase can refer to any URL, not just one that is relative to a known URL, the value of the RMI codebase must be an absolute URL to the location of the stub class and any other classes needed by the stub class. This value of the codebase property can refer to:
  • The URL of a directory in which the classes are organized in package-named sub-directories
  • The URL of a JAR file in which the classes are organized in package-named directories
  • A space-delimited string containing multiple instances of JAR files and/or directories that meet the criteria above
Note: When the codebase property value is set to the URL of a directory, the value must be terminated by a "/".

Examples

If the location of your downloadable classes is on an HTTP server named "webvector", in the directory "export" (under the web root), your codebase property setting might look like this:
-Djava.rmi.server.codebase=http://webvector/export/
If the location of your downloadable classes is on an HTTP server named "webline", in a JAR file named "mystuff.jar", in the directory "public" (under the web root), your codebase property setting might look like this:
-Djava.rmi.server.codebase=http://webline/public/mystuff.jar
Now let's suppose that the location of your downloadable classes has been split between two JAR files, "myStuff.jar" and "myOtherStuff.jar". If these JAR files are located on different servers (named "webfront" and "webwave"), your codebase property setting might look like this:
-Djava.rmi.server.codebase="http://webfront/myStuff.jar http://webwave/myOtherStuff.jar"

6.0 Troubleshooting tips

Any serializable class, including RMI stubs, can be downloaded if your RMI programs are configured properly. Here are the conditions under which dynamic stub downloading will work:
  1. The stub class and any of the classes that the stub relies on are served up from a URL reachable from the client.
  2. The java.rmi.server.codebase property has been set on the server program (or in the case of activation, the "setup" program) that makes the call to bind or rebind, such that:
    • The value of the codebase property is the URL in step A and
    • If the URL specified as the value of the codebase property is a directory, it must end in a trailing "/"
  3. The rmiregistry cannot find the stub class or any of the classes that the stub relies on in its CLASSPATH. This is so the codebase gets annotated to the stub when the registry does its class load of the stub, as a result of calls to bind or rebind in the server or setup code.
  4. The client has installed a SecurityManager that allows the stub to be downloaded. In the Java 2 SDK, Standard Edition, v1.2 and later this means that the client must also have a properly configured security policy file.
There are two common problems associated with the java.rmi.server.codebase property, which are discussed next.

6.1 If you encounter a problem running your RMI server

The first problem you might encounter is the receipt of a ClassNotFoundException when attempting to bind or rebind a remote object to a name in the registry. This exception is usually due to a malformed codebase property, resulting in the registry not being able to locate the remote object's stubs or other classes needed by the stub.
It is important to note that the remote object's stub implements all the same interfaces as the remote object itself, so those interfaces, as well as any other custom classes declared as method parameters or return values, must also be available for download from the specified codebase.
Most frequently, this exception is thrown as a result of omitting the trailing slash from the URL value of the property. Other reasons would include: the value of the property is not a URL; the path to the classes specified in the URL is incorrect or misspelled; the stub class or any other necessary classes are not all available from the specified URL.
The exception that you may encounter in such a case would look like this:
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: examples.callback.MessageReceiverImpl_Stub
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: examples.callback.MessageReceiverImpl_Stub
java.lang.ClassNotFoundException: examples.callback.MessageReceiverImpl_Stub
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Compiled Code)
at sun.rmi.transport.StreamRemoteCall.executeCall(Compiled Code)
at sun.rmi.server.UnicastRef.invoke(Compiled Code)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Compiled Code)
at java.rmi.Naming.rebind(Compiled Code)
at examples.callback.MessageReceiverImpl.main(Compiled Code)
RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: examples.callback.MessageReceiverImpl_Stub

6.2 If you encounter a problem running your RMI client

The second problem you could encounter is the receipt of a ClassNotFoundException when attempting to lookup a remote object in the registry. If you receive this exception in a stacktrace resulting from an attempt to run your RMI client code, then your problem is the CLASSPATH with which your RMI registry was started. See requirement C in section 6.0. Here is what the exception will look like:
java.rmi.UnmarshalException: Return value class not found; nested exception is:
java.lang.ClassNotFoundException: MyImpl_Stub
at sun.rmi.registry.RegistryImpl_Stub.lookup(RegistryImpl_Stub.java:109
at java.rmi.Naming.lookup(Naming.java:60)
at RmiClient.main(MyClient.java:28)

Other resources

If you your codebase questions are still unanswered, please take a look through the archives of the rmi-users email list first.
You may wish to subscribe to the rmi-users email list.
We are very interested in knowing whether these tutorials are useful. Please send any comments or suggestions to: rmi-comments@java.sun.com, with a subject of "codebase tutorial".
*As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com

http://java.sun.com/j2se/1.4.2/docs/guide/rmi/codebase.html#sixStepC

vendredi 20 novembre 2009

【转】Java » 文件输入输出 » 文件

1. 创建文件


2. 创建一个临时文件


3. 创建一个临时文件并删除它退出


4. 创建一个目录(或几个目录)


5. 获取文件大小


6. 变更文件或目录上次修改的时间


7. 构建文件路径


8. 创建临时文件指定的扩展名后缀


9. 创建临时文件中指定的目录


10. 创建新的空文件


11. 比较两个文件路径


12. 删除文件


13. 删除目录(空目录)


14. 删除文件或目录时,虚拟机终止


15. 确定文件或目录


16. 确定文件是否可以读取


17. 确定文件是否可以这样写:


18. 判断是否存在文件或目录


19. 确定文件或目录是隐藏


20. 证明文件


21. 移动文件或目录到另一个目录


22. 查找目录


23. 从java.io.File获得所有的路径信息


24. Getting an Absolute Filename Path from a Relative Filename Path


25. Getting an Absolute Filename Path from a Relative Filename with Path


26. Getting an Absolute Filename Path from a Relative Filename parent Path


27. 获得绝对文件的路径


28. 获取以字节为单位文件大小


29. 获取父目录的File对象


30. 取得文件最后修改日期


31. File.getCanonicalFile() converts a filename path to a unique canonical form suitable for comparisons.


32. Getting the Parents of a Filename Path


33. Get the parents of an absolute filename path


34. Getting and Setting the Modification Time of a File or Directory


35. 制作只读文件或目录


36. 文件根列表


37. 驱动器列表


38. 列出目录内容


39. 重命名文件或目录


40. 迫使更新一个文件到磁盘


41. 随机文件


42. 创建一个目录;所有祖先目录必须存在


43. Create a directory; all non-existent ancestor directories are automatically created


44. 获取当前的工作目录


45. 改变文件属性为可写


46. 数据文件


47. 输出到一个文本文件


48. 选择文件


49. 读取文本文件数据


50. 复制文件


51. 查询文件信息


52. Working with RandomAccessFile


53. 获取文件列表,并检查是否任何文件丢失


54. 从Java删除文件


55. Java中临时文件


56. 比较文件日期


57. 排序文件,基于他们的最后修改日期


58. 字符串-提取打印二进制文件字符串


59. 得到扩展名,路径和文件名


60. 读取文件内容字符串使用输入输出工具


61. Get all xml files by file extension


62. 文件名组件


63. 获取文件类型图标


64. 改变文件属性为只读


65. 获取文件扩展名


66. 递归的搜索文件


67. 创建一个人类可读的文件大小


68. 设置文件属性

mardi 20 octobre 2009

[转]Install Java 6 on Mac OS X Leopard

Installation

Java 6 isn’t installed by default. Java 6 is available as a simple Software Update, so if your system is up to date, Java 6 is installed, else upgrade your system. Note that Java SE 6 won’t appear for users on 32-bit Intel machines (Intel Core and Intel Core Duo) even if their systems are fully up to date.

Activation

Even though Java 6 is installed, Java 5 is still used by Mac OS X. You have to activate Java 6 by yourself. To do this, you need to run :
Applications -> Utilities -> Java -> Java Preferences
You will get the following window :

You just need to change the order of Java versions to use (Java application versions). Once Java SE 6 is on the top of the list, it should be activated.

Verification

You can check that Java 6 is correctly activated. You need to run a terminal (Applications -> Utilities -> Terminal) and to type the command: java -version
You should get this message :

jeudi 9 juillet 2009

HOCL COMPILER 安装问题的解决方法

在编译HOCL 编译器成功后,创建自己的HOCL 文档,之后在文件夹中输入以下命令:

make -f Makefile

也许会显示以下错误: ...fault: 5.0...

说明JAVA 编译器出了问题, 一是安装了老板本, 如果确认已经安装了最新版本, 则需要设置系统变量.

solution: 在终端输入:
java -version
javac -version
看看这两个是不是都是1.6.0, 如果不是,需要设置.

第一步,查看Java 是否安装好.
执行:

java -version

会显示当前版本,如果与已安装的版本不同,则需要重新设置环境变量.

现检查环境变量,输入以下三条命令:

echo $PATH
echo $CLASSPATH
echo $JAVA_HOME

看看以上三个变量分别是什么.
正确的结果是:
$PATH=/urs/lib/jvm/java-6-sun/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
$CLASSPATH=JAVA_HOME/lib.tools.jar
$JAVA_HOME=/etc/lib/jvm/java-6-sun

如果不是,需要设置:

sudo vi /etc/profile

# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

if [ -d /etc/profile.d ]; then
for i in /etc/profile.d/*.sh; do
if [ -r $i ]; then
. $i
fi
done
unset i
fi

if [ "$PS1" ]; then
if [ "$BASH" ]; then
PS1='\u@\h:\w\$ '
if [ -f /etc/bash.bashrc ]; then
. /etc/bash.bashrc
fi
else
if [ "`id -u`" -eq 0 ]; then
PS1='# '
else
PS1='$ '
fi
fi
fi

加入:
export JAVA_HOME=/usr/lib/jvm/java-6-sun
PATH=/urs/lib/jvm/java-6-sun/bin:$PATH
export CLASSPATH=JAVA_HOME/lib.tools.jar

umas k022

这样可以解决java -version 不是1.6.0 的问题;

第二步:javac -version
有可能出现Eclipse Java Compiler V_... 3.2.2 release, Copyright IBM Corp 2000, 2006...

如果是这种情况, 我们需要恢复:
在Terminal 输入以下命令:

sudo update-java-alternatives -s java-6-sun

然后再执行:
javac -version

可以看到已经显示了:javac 1.6.0

解决!