- 论坛徽章:
- 0
|
JNI方法的初次接触。。。
下面简单介绍通过使用JNI如何判断系统盘符的类型的实现步骤:
1:编写文件DriveType.java, 代码如下:
package learn;
public class DriveType
{
/** dll name */
private static final String _dllName = "DriveType";
/**
* Retrieves the specified drive's type.
*
* @param drive a String that specifies the
* root directory of the disk to return the drive type
* information about. If drive is null
* the method uses the root of the current directory.
* @return an int that specifies the drive type
*/
public static native int getDriveType(String drive);
static
{
System.loadLibrary(_dllName);
}
}
2: 在console下运行D:learn>javac DriveType.java 生成DriveType.class, 然后运行
D:learn>javah –jni DriveType, 自动生成DriveType.h的头文件。
3:编写C代码DriveType.c, 具体如下:
#include "DriveType.h"
#define STRICT
#include
JNIEXPORT jint JNICALL Java_ learn _DriveType_getDriveType(JNIEnv *env, jclass obj, jstring drive)
{
const char *str = NULL;
UINT uReturn;
str = (*env)->GetStringUTFChars(env, drive, 0);
uReturn = GetDriveType(str);
(*env)->ReleaseStringUTFChars(env, drive, str);
return uReturn;
}
这里要注意的是,函数名称里一定要加上包名learn,否则编译运行的话会出现找不到GetDriveType这个方法的异常。这个异常困扰了我很久才发现的,汗阿!
4:现在就可以用VC的命令行编译器cl来把DriveType.c编译成dll了。
使用命令:
D:learn>cl -Ic:j2sdk1.4.2_07include -Ic:j2sdk1.4.2_07includewin32 -LD Driv
eType.c -FeDriveType.dll
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.
DriveType.c
Microsoft (R) Incremental Linker Version 7.10.3077
Copyright (C) Microsoft Corporation. All rights reserved.
/dll
/implib:DriveType.lib
/out:DriveType.dll
DriveType.obj
Creating library DriveType.lib and object DriveType.exp
看到这样的输出就说明编译成功了。
5: 然后可以把生成的DriveType.dll考到java 的某个libpath里,如jdk的bin目录,或者是系统的system32目录下等等。
6:最后可以写个测试程序DriveTypeTest.java, 代码如下:
package learn;
import java.io.File;
class DriveTypeTest
{
/**
* The drive type cannot be determined.
*/
public static final int DRIVE_UNKNOWN = 0;
/**
* The root directory does not exist.
*/
public static final int DRIVE_NO_ROOT_DIR = 1;
/**
* The disk can be removed from the drive.
*/
public static final int DRIVE_REMOVABLE = 2;
/**
* The disk cannot be removed from the drive.
*/
public static final int DRIVE_FIXED = 3;
/**
* The drive is a remote (network) drive.
*/
public static final int DRIVE_REMOTE = 4;
/**
* The drive is a CD-ROM drive.
*/
public static final int DRIVE_CDROM = 5;
/**
* The drive is a RAM disk.
*/
public static final int DRIVE_RAMDISK = 6;
public static void main(String[] args)
{
File[] roots = File.listRoots();
for(int i = 0; i
File root = roots;
String name = root.getPath();
System.out.println(name+" : " + DriveType.getDriveType(name));
}
}
}
大家可以通过看输出的数字来判别是哪种类型的Drive了。
主要步骤就是这么些,上面有些代码是参考网上的J,希望对大家有所帮助,至少可以熟悉一下JNI方法的基本实现步骤。
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/8401/showart_47598.html |
|