最近中文字幕完整版高清,宅男宅女精品国产av天堂,亚洲欧美日韩综合一区二区,最新色国产精品精品视频,中文字幕日韩欧美就去鲁

首頁 > 考試輔導 > 計算機考試 > JAVA認證 > JAVA認證交流指導 > JNI調(diào)用C/C++方法從控制臺輸入密碼

JNI調(diào)用C/C++方法從控制臺輸入密碼

        最近看到一個問題,如何用java實現(xiàn)從控制臺輸入密碼?
    本來以為是很簡單的問題,查了一下發(fā)現(xiàn)java居然沒提供這樣一個方法。目前實現(xiàn)的方式有2個,一個是利用jni來調(diào)用c/c++方法,另一個是使用多線程。
下面是使用jni的方法:
首先,寫出我們的java類:


public   class  jnipasswordreader  {

     private   native  string readpassword();
     static {
        system.loadlibrary( " passworddll " );
    }
     / */ /
     *  @param  args
      */
     public   static   void  main(string[] args)  {
         //  todo auto-generated method stub
        jnipasswordreader reader  =   new  jnipasswordreader();
        string pwd  =  reader.readpassword();
        system.out.println( " \nyour password is: "   +  pwd);
    }

}

    這一段使用system.loadliberary("..");來加載本地類庫,passworddll是文件名,不需要加dll后綴,系統(tǒng)會自動辨認。

編譯成jnipasswordreader.class以后,使用
javah -jni jnipasswordreader
命令,生成一個jnipasswordreader.h文件,文件內(nèi)容如下:

// /*  do not edit this file - it is machine generated  */
#include  < jni.h >
// /*  header for class jnipasswordreader  */

#ifndef _included_jnipasswordreader
#define  _included_jnipasswordreader
#ifdef __cplusplus
extern   " c "   {
#endif
// /*
 * class:     jnipasswordreader
 * method:    readpassword
 * signature: ()ljava/lang/string;
  */
jniexport jstring jnicall java_jnipasswordreader_readpassword
  (jnienv  * , jobject);

#ifdef __cplusplus
}
#endif
#endif

然后,我們需要寫一個cpp文件來實現(xiàn)
jniexport jstring jnicall java_jnipasswordreader_readpassword  (jnienv *, jobject);
接口。
于是,我寫了一個passworddll.cpp文件,內(nèi)容如下:

//  這是主 dll 文件。
#include  " stdafx.h "
#include  " jnipasswordreader.h "
#include  < iostream >
#include  < iomanip >
#include  < conio.h >
using   namespace  std;

// /*
 * class:     jnipasswordreader
 * method:    readpassword
 * signature: ()v
  */
jniexport jstring jnicall java_jnipasswordreader_readpassword
  (jnienv  *  env, jobject) {
       char  str[ 20 ]  =   { 0 } ; 
    jstring jstr;
     char  ch;
     char   * pstr  =  str;
     while ( true )
     {
        ch  =  getch();
         if (isdigit(ch) || isalpha(ch))
         {
            cout << " * " ;
             * pstr ++   =  ch;
        }
         else   if (ch  ==   ' \b '   &&  pstr  >  str)
         {
             * ( -- pstr)  =   0 ;
            cout << " \b \b " ;
        }
         else   if (ch  ==   0x0a   ||  ch  ==   0x0d )
         {
             break ;
        }
    }
    jstr  =  env -> newstringutf(str);
     return  jstr;
}

    我使用vs2005來生成對應(yīng)的dll文件,在生成之前,需要把$jdk_home/include/jni.h和$jdk_home/include/win32/jni_md.h這兩個文件copy到microsoft visio studio 8/vc/include目錄下,我就在這里卡了大概1個小時,一直說找不到j(luò)ni.h文件

   然后就可以使用vs2005來生成dll了,生成好對應(yīng)的passworddll.dll以后,把該dll文件放到系統(tǒng)變量path能找到的地方,比如windows/system32/或者jdk/bin目錄,我是放到j(luò)dk_home/bin下面了
放好以后,
執(zhí)行java jnipasswordreader
就可以輸入密碼了。