Android内核开发 Linux Java编程调用内核模块设备驱动

本文出处: http://blog.csdn.net/leytton/article/details/52738760

本文目的为Linux系统环境下:1、编写内核模块程序并编译 2、加载内核模块 3、编写Java程序调用内核模块

功能为向内核模块虚拟设备写字符串,再从内核模块虚拟设备读出字符串长度。


1、编译加载内核模块

见另文《 Android内核开发 Linux C编程调用内核模块设备驱动》http://blog.csdn.net/leytton/article/details/52738901


2、WordCount.java文件

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class WordCount {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length > 0) {
			if (writeStringToDev(args[0])) {
				System.out.println("写入成功");
			} else {
				System.out.println("写入失败");
				return;
			}
			int result = readWordCountFromDev();
			if (result > -1) {
				System.out.println("字符串长度为:" + result);
			} else {
				System.out.println("读取失败");
				return;
			}
		} else {
			System.out.println("Usage .eg:java WordCount \"hello\"");
		}
	}

	// 向/dev/wordcount设备文件中写入字符串
	private static boolean writeStringToDev(String str) {
		try {
			// 打开/dev/word_count设备文件
			FileOutputStream fos = new FileOutputStream("/dev/word_count");
			// 写入字符串
			fos.write(str.getBytes("iso-8859-1"));
			fos.close();
		} catch (Exception e) {
			System.out.println("Error:" + e.getMessage());
			return false;
		}
		return true;
	}

	// 读取/dev/wordcount设备文件中的字符串长度
	private static int readWordCountFromDev() {
		int word_count = -1;
		byte[] buffer = new byte[4];
		try {
			// 打开/dev/wordcount设备文件
			FileInputStream fis = new FileInputStream("/dev/word_count");
			word_count = fis.read();
			fis.close();
		} catch (Exception e) {
			System.out.println("Error:" + e.getMessage());
			return -1;
		}
		return word_count;
	}

}

3、Linux中编译并运行

[hadoop@localhost drivers01]$ javac -encoding gbk WordCount.java 
[hadoop@localhost drivers01]$ sudo java WordCount "I love you"
写入成功
字符串长度为:10
[hadoop@localhost drivers01]$

4、参考文章

《使用Android NDK和Java测试Linux驱动》http://blog.csdn.net/nokiaguy/article/details/8671397

posted @ 2016-10-05 20:57  Leytton  阅读(226)  评论(0编辑  收藏  举报