Rising Sun

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  148 随笔 :: 0 文章 :: 22 评论 :: 0 Trackbacks

2013年12月25日 #

     摘要: 看了网上的许多对于lucene 分词解析的文章一知半解且代码比较老旧,为透彻、系统、全面、深刻的了解分词是怎么一个过程,通过自定义一个分词器来分析理解。 其中分词部分利用ICTCLAS4j接口实现。结构如下所示:            要实现自定义的ICTCLAS4jAnalyzer必须继承Analy...  阅读全文
posted @ 2015-01-07 10:11 brock 阅读(1084) | 评论 (0)编辑 收藏

Lucene Directory类就像它的意思一样“目录”,如“目录”不存在,第一次启动被创建,一旦文件被创建,它只能打开阅读,或删除。允许读取和写入随机访问。Java I/O api 不能直接使用,只能通过这个API Directory的实现类可以分为文件目录,内存目录和目录的代理类及工具类。具体如下图所示:


一:文件目录

SimpleFSDirectory:FSDirectory的简单实现,并发能力有限,遇到多线程读同一个文件时会遇到瓶颈,通常用NIOFSDirectoryMMapDirectory代替。

NIOFSDirectory:通过java.nio's FileChannel实行定位读取,支持多线程读(默认情况下是线程安全的)。该类仅使用FileChannel进行读操作,写操作则是通过FSIndexOutput实现。

注意:NIOFSDirectory 不适用于Windows系统,另外如果一个访问该类的线程,在IO阻塞时被interruptcancel,将会导致底层的文件描述符被关闭,后续的线程再次访问NIOFSDirectory时将会出现ClosedChannelException异常,此种情况应用SimpleFSDirectory代替。

MMapDirectory:通过内存映射进行读,通过FSIndexOutput进行写的FSDirectory实现类。使用该类时要保证用足够的虚拟地址空间。另外当通过IndexInputclose方法进行关闭时并不会立即关闭底层的文件句柄,只有GC进行资源回收时才会关闭。

 

为了能适应各个操作系统选择最佳Directory方案,lucene 提供FSDirectory类的静态方法open()实现自适应。

 public static FSDirectory open(File path, LockFactory lockFactory) throws IOException {

    if ((Constants.WINDOWS || Constants.SUN_OS || Constants.LINUX)

          && Constants.JRE_IS_64BIT && MMapDirectory.UNMAP_SUPPORTED) {

      return new MMapDirectory(path, lockFactory);

    } else if (Constants.WINDOWS) {

      return new SimpleFSDirectory(path, lockFactory);

    } else {

      return new NIOFSDirectory(path, lockFactory);

    }

  }

二:内存目录

RAMDirectory:常驻内存的Directory实现方式。默认通过SingleInstanceLockFactory(单实例锁工厂)进行锁的实现。该类不适合大量索引的情况另外也不适用于多线程的情况 在索引数据量大的情况下建议使用MMapDirectory代替。RAMDirectoryDirectory抽象类在使用内存最为文件存储的实现类,其主要是将所有的索引文件保存到内存中。这样可以提高效率。但是如果索引文件过大的话,则会导致内存不足,因此,小型的系统推荐使用,如果大型的,索引文件达到G级别上,推荐使用FSDirectory

NRTCachingDirectory:是对RAMDirectory的封装,适用于近乎时时(near-real-time)操作的环境。

三:Direcotry的代理类及工具类

FileSwitchDirectory:文件切换的Directory实现.针对lucene的不同的索引文件使用不同的Directory .借助FileSwitchDirectory整合不同的Directory实现类的优点于一身
比如MMapDirectory,借助内存映射文件方式提高性能,但又要减少内存切换的可能 ,当索引太大的时候,内存映射也需要不断地切换,这样优点也可能变缺点,而之前的NIOFSDirectory实现java NIO的方式提高高并发性能,但又因高并发也会导致IO过多的影响,所以这次可以借助FileSwitchDirectory发挥他们两的优点。

RateLimitedDirectoryWrapper:通过IOContext来限制读写速率的Directory封装类。

CompoundFileDirectory:用于访问一个组合的数据流。仅适用于读操作。对于同一段内扩展名不同但文件名相同的所有文件合并到一个统一的.cfs文件和一个对应的.cfe文件内。
.cfs文件由HeaderFileDataFileCount组成。.cfe文件由HeaderFileCount,FileName,DataOffset,DataLength组成。.cfs文件中存储着索引的概要信息及组合文件
的数目(FileCount)。.cfe文件存储文件目录的条目内容,内容中包括文件数据扇区的起始位置,文件的长度及文件的名称。

TrackingDirectoryWrapperDirectory的代理类。用于记录哪些文件被写入和删除。

四:Direcotry读写对象的类图




 文章转载过来的!

posted @ 2015-01-07 10:09 brock 阅读(264) | 评论 (0)编辑 收藏

    本机已经安装了jdk1.6,而比较早期的项目需要依赖jdk1.5,于是同时在本机安装了jdk1.5和jdk1.6. 

 安装jdk1.5前,执行java -version得到

java version "1.6.0_38"
Java(TM) SE Runtime Environment (build 1.6.0_38-b05)
Java HotSpot(TM) 64-Bit Server VM (build 20.13-b02, mixed mode)


安装完jdk1.5,并修改环境变量JAVA_HOME为D:\devSoftware\jdk1.5.再执行 java -version时,依然显示:

java version "1.6.0_38"
Java(TM) SE Runtime Environment (build 1.6.0_38-b05)
Java HotSpot(TM) 64-Bit Server VM (build 20.13-b02, mixed mode)


看上去,新的环境变量JAVA_HOME=D:\devSoftware\jdk1.5并没有生效。 在网上找了很多资料才发现:

      在安装JDK1.6时(本机先安装jdk1.6再安装的jdk1.5),自动将java.exe、javaw.exe、javaws.exe三个可执行文件复制到了C:\Windows\System32目录,由于这个目录在WINDOWS环境变量中的优先级高于JAVA_HOME设置的环境变量优先级


解决方案:将java.exe,javaw.exe,javaws.exe删除即可。开启新的命令行窗口,再执行java -version时,就得到了期望中的结果

java version "1.5.0_17"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_17-b04)
Java HotSpot(TM) 64-Bit Server VM (build 1.5.0_17-b04, mixed mode)


posted @ 2015-01-06 11:45 brock 阅读(7010) | 评论 (0)编辑 收藏

在学lucene 之初看了许多书,都是走马观花,没有项目的驱动下,来一个用例demo感觉也不是很难,“我会了”这是我的第一感觉。

         2013年底公司接到一个项目用到lucene,这是我第一次正真接触Lucene,代码比较老3.6版本,不适合新项目的需求(空间查询)。于是下载了最新版本 4.51,有带“空间查询”模块。各大搜索引擎都没有找到像样例子,于是想到了lucene svn trunk目录测试用例中找到了测试例子,开始了一段lucene之旅。

 

写数据,创建IndexWriter,通过它的构造函数需要一个索引目录(Diectory)和索引写入配置项(InderWriterConfig,直接上代码:

//设置写入目录(好几种呵呵)

Directory d=FSDirectory.open(new File("D:/luceneTest"));

//设置分词 StandardAnalyzer(会把句子中的字单个分词)

Analyzer analyzer= new StandardAnalyzer(Version.LUCENE_45);

//设置索引写入配置

IndexWriterConfig config=new IndexWriterConfig(Version.LUCENE_45,analyzer);

//设置创建模式

//config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);

IndexWriter indexwriter= new IndexWriter(d,config);

 

    上面四行代码就创建好了indexwriter下面把数据填入就好了,写入有多种方式如下图:


         addDocment 举例代码如下:

Document doc=new Document(); 

        doc.add(new StringField("id", "1", Store.YES));

        doc.add(new StringField("name", "brockhong", Store.YES));

        doc.add(new TextField("content", "lucene 文档第一次写看着给分吧", Store.YES)); 

//写入数据

indexwriter.addDocument(doc);

//提交

indexwriter.commit();

Luke 工具查看Text列,这是标准分词惹的祸哦!写入成功。


         读数据查询,创建 IndexSearcher 构造函数设置indexReader ,输入查询条件,上面content字段数据设置了分词,所以必须通过查询解析类QueryParser设定分词字段、版本、分词模式,并通过parse方法得到查询条件。代码如下:       

 //读数据

 //创建 indexReader 这个已过时 IndexReader.open(d),里面的代码一样可能为了兼容老版本

 IndexReader indexReader = DirectoryReader.open(d);

 IndexSearcher indexSearcher = new IndexSearcher(indexReader);

//查询 设置分词字段

QueryParser queryParser = new QueryParser(Version.LUCENE_45, "content",

                   new StandardAnalyzer(Version.LUCENE_45));

 //or 关系 “给”、“分”

         queryParser.setDefaultOperator(QueryParser.OR_OPERATOR);

Query query = queryParser.parse("给分");

 

TopDocs results = indexSearcher.search(query, 100);

int numTotalHits = results.totalHits;

System.out.println(" " + numTotalHits + " 完全匹配的文档");

ScoreDoc[] hits = results.scoreDocs;

for (int i = 0; i < hits.length; i++) {

              Document document = indexSearcher.doc(hits[i].doc);

              System.out.println("content:" + document.get("content"));

}


pasting
posted @ 2014-12-31 17:07 brock 阅读(321) | 评论 (0)编辑 收藏

http://blog.csdn.net/ablipan/article/details/8198692

使用SAXReader的read(File file)方法时,如果xml文件异常会导致文件被服务器占用不能移动文件,建议不使用read(File file)方法而使用read(FileInputStream fis)等流的方式读取文件,异常时关闭流,这样就不会造成流未关闭,文件被锁的现象了。(在服务器中运行时会锁住文件,main方法却不会)。


1、以下方式xml文件异常时会导致文件被锁

  1.                    Document document = null;  
  2. File file = new File(xmlFilePath);  
  3. SAXReader saxReader = new SAXReader();  
  4. try  
  5. {  
  6.     document = saxReader.read(file);  
  7. } catch (DocumentException e)  
  8. {  
  9.     logger.error("将文件[" + xmlFilePath + "]转换成Document异常", e);  
  10. }  


2、以下方式xml文件异常时不会锁文件(也可以使用其他的流来读文件)

  1.                 Document document = null;  
  2. FileInputStream fis = null;  
  3. try  
  4. {  
  5.     fis = new FileInputStream(xmlFilePath);  
  6.     SAXReader reader = new SAXReader();  
  7.     document = reader.read(fis);  
  8. }   
  9. catch (Exception e)  
  10. {  
  11.     logger.error("将文件[" + xmlFilePath + "]转换成Document异常", e);  
  12. }   
  13. finally  
  14. {  
  15.     if(fis != null)  
  16.     {  
  17.         try  
  18.         {  
  19.             fis.close();  
  20.         } catch (IOException e)  
  21.         {  
  22.             logger.error("将文件[" + xmlFilePath + "]转换成Document,输入流关闭异常", e);  
  23.         }  
  24.     }  
  25. }  
posted @ 2014-09-02 14:00 brock 阅读(473) | 评论 (0)编辑 收藏

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>二次开发示例</title>
<link rel="stylesheet" href="../OpenLayers2.11/theme/default/style.css" type="text/css" />
    <script type="text/javascript" src="../OpenLayers2.11/OpenLayers.js"></script>
    <script type="text/javascript" src="../OpenLayers2.11/OpenLayersEx.js?random=8852c822-1ab8-4c0a-9717-b6f4c2b98115"></script>
 
    <!-- Import OpenLayers, reduced, wms read only version -->
    <!--<script src="../OpenLayers.js" type="text/javascript"></script>-->
<script type="text/javascript">
   var map;
var bounds = new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34);
function init() {
    var options = {
                       controls:[new OpenLayers.Control.XPanZoomBar(),new OpenLayers.Control.Navigation(),new OpenLayers.Control.MousePosition({numDigits:2})] ,
                        projection: 'EPSG:900913',
                        maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
                        maxResolution: 156543.0339,
                        units: 'm',
                        zoomLevel: 8
                    };
    map = new OpenLayers.Map('map',options);    
    
/*{
        div: "map",
        projection: "EPSG:900913",
        units: "m",
        maxExtent: new OpenLayers.Bounds(
            -20037508.34, -20037508.34, 20037508.34, 20037508.34
        ),
        maxResolution: 156543.0339,
zoomLevel: 8
    }*/
   // var osm = new OpenLayers.Layer.OSM();
    // If tile matrix identifiers differ from zoom levels (0, 1, 2, ...)
    // then they must be explicitly provided.
    var matrixIds = new Array(19);
    for (var i=0; i<16; ++i) {
        matrixIds[i] = i+"";
    }
var wmts2 = new OpenLayers.Layer.WMTS({
        name: "Medford Buildings",
        url: "http://t0.tianditu.com/cia_w/wmts",
        layer: "cia",
        matrixSet: "w",
        matrixIds: matrixIds,
        format: "tiles",
        style: "default",
        opacity: 0.7,
        isBaseLayer: false
    });       
    var wmts = new OpenLayers.Layer.WMTS({
        name: "vec",
        url: "http://t0.tianditu.com/vec_w/wmts",
        layer: "vec",
        matrixSet: "w",
        matrixIds: matrixIds,
        format: "tiles",
        style: "default",
        opacity:1,
        isBaseLayer: true
    });                
    map.addLayers( [wmts,wmts2]);
  //  map.addControl(new OpenLayers.Control.LayerSwitcher());
  //  map.setCenter(new OpenLayers.LonLat(13391734.740566667,3535411.228859166),7);
map.moveTo(new OpenLayers.LonLat(13391734.740566667,3535411.228859166),7);
}
</script>
</head>
 <body onload="init();">
        <h1 id="title">Web Map Tile Service (WMTS) Layer</h1>
        
    
        
        <div id="map" class="smallmap"></div>
        
       
    </body>
</html>
posted @ 2014-06-24 17:00 brock 阅读(818) | 评论 (0)编辑 收藏

arcgis

CGCS2000_3_Degree_GK_Zone_40

WKID: 4528 Authority: EPSG

 

Projection: Gauss_Kruger

False_Easting: 40500000.0

False_Northing: 0.0

Central_Meridian: 120.0

Scale_Factor: 1.0

Latitude_Of_Origin: 0.0

Linear Unit: Meter (1.0)

 

Geographic Coordinate System: GCS_China_Geodetic_Coordinate_System_2000

Angular Unit: Degree (0.0174532925199433)

Prime Meridian: Greenwich (0.0)

Datum: D_China_2000

  Spheroid: CGCS2000

    Semimajor Axis: 6378137.0

    Semiminor Axis: 6356752.314140356

Inverse Flattening: 298.257222101

 

Java 自定义

 

String [] proj4_w = new String [] { 

"+proj=tmerc", 
"+lat_0=0", 
"+lon_0=120", 
"+ellps=GRS80", 
"+units=m", 
"+x_0=40500000",
"+y_0=0",
"+k=1.0"
};

经纬度转换

       ///+proj=tmerc +lat_0=0 +lon_0=120 +k=1 +x_0=40500000 +y_0=0 +ellps=GRS80 +units=m +no_defs

                Point2D.Double srcProjec = null;

                Point2D.Double dstProjec = null;

                Projection proj = ProjectionFactory.fromPROJ4Specification (proj4_w);

//  "epsg:4528" 数据从proj4 拷贝 nad

//      Point2D.Double srcProjec = null;

//      Point2D.Double dstProjec = null;

//      Projection proj = ProjectionFactory.getNamedPROJ4CoordinateSystem ("epsg:4528");

 

        srcProjec = new Point2D.Double (120.159,30.267);

        //40515348.2903 3349745.5395

       

        dstProjec = proj.transform (srcProjec, new Point2D.Double ());

        System.out.println ("TM:" + dstProjec);

    // TM: Point2D.Double [644904.399587292, 400717.8948938238]

 

        srcProjec = new Point2D.Double (40515348.2903 ,3349745.5395);

        dstProjec = proj.inverseTransform (srcProjec, new Point2D.Double ());

       

        System.out.println ("TM:" + dstProjec);

posted @ 2014-06-20 11:41 brock 阅读(3711) | 评论 (0)编辑 收藏

今天研究Oracle遇到了这个问题ora-01033:oracle initializationor shutdown in progress

ORA-01033:ORACLEinitialization or shutdown in progress

解决方法

1)开始-运行-cmd

2)命令行中输入SQLPLUS SYS/SYS AS SYSDBA

3)输入SHUTDOWN

4)输入STARTUP.注意这里是最重要的地方,在显示相关数据后,它还会显示为什么不能启动的错误所在.

 

C:\Users\lenovo>SQLPLUSSYS/SYS AS SYSDBA

SQL*Plus: Release 10.2.0.3.0 - Production on星期三 7月 3 11:43:32 2013

Copyright (c) 1982, 2006, Oracle.  All Rights Reserved.

连接到:

Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 -Production

With the Partitioning, OLAPand Data Mining options

SQL> SHUTDOWN

ORA-01109:数据库未打开

已经卸载数据库。

ORACLE例程已经关闭。

SQL> STARTUP

ORACLE例程已经启动。

Total System Global Area 293601280 bytes

Fixed Size                 1290208 bytes

Variable Size            234881056 bytes

Database Buffers           50331648 bytes

Redo Buffers               7098368 bytes

数据库装载完毕。

ORA-01157:无法标识/锁定数据文件 6 - 请参阅 DBWR 跟踪文件

ORA-01110:数据文件 6: 'F:\DC\DB\SDRS\TS_SDRS.DBF'

SQL> alter databasedatafile'F:\DC\DB\SDRS\TS_SDRS.DBF'offline drop;

 

数据库已更改。

 

SQL> alter database open;

 

数据库已更改。

 

SQL> drop tablespaceTS_SDRS including contents;

 

表空间已删除。

SQL> create undo tablespace TS_SDRS

  2  datafile'CracleoradatasmsdbUNDOTBS01.DBF'size 2048M extent management local;

 

表空间已创建。

 

SQL> alter system setundo_tablespace=TS_SDRS;

 

系统已更改。

 

SQL> shutdown

数据库已经关闭。

已经卸载数据库。

ORACLE例程已经关闭。

SQL> startup

ORACLE例程已经启动。

 

Total System Global Area  293601280 bytes

Fixed Size                 1290208 bytes

Variable Size            243269664 bytes

Database Buffers          41943040 bytes

Redo Buffers               7098368 bytes

数据库装载完毕。

数据库已经打开。

SQL>


------------------
ORA-01245、ORA-01547错误的解决            

数据库rman restore database 之后,执行recover database的时候,报告ORA-01245错误,详细的错误信息如下:


SQL> recover database until cancel;
ORA-00279: change 575876 generated at 12/01/2009 08:19:49 needed for thread 1
ORA-00289: suggestion :
/oracle/flash_recovery_area/ORCL/archivelog/2009_12_01/o1_mf_1_2_%u_.arc
ORA-00280: change 575876 for thread 1 is in sequence #2


Specify log: {=suggested | filename | AUTO | CANCEL}
auto
ORA-00308: cannot open archived log
'/oracle/flash_recovery_area/ORCL/archivelog/2009_12_01/o1_mf_1_2_%u_.arc'
ORA-27037: unable to obtain file status
Linux Error: 2: No such file or directory
Additional information: 3


ORA-00308: cannot open archived log
'/oracle/flash_recovery_area/ORCL/archivelog/2009_12_01/o1_mf_1_2_%u_.arc'
ORA-27037: unable to obtain file status
Linux Error: 2: No such file or directory
Additional information: 3


ORA-01547: warning: RECOVER succeeded but OPEN RESETLOGS would get error below
ORA-01245: offline file 2 will be lost if RESETLOGS is done
ORA-01110: data file 2: '/oracle/oradata/orcl/undotbs01.dbf'


SQL>

 

[@more@]

检查ORA-01245那一行,发现是datafile 2状态为offline,解决的方法就是首先将datafile 2 online,然后再recover database。

SQL> alter database datafile 2 online;

Database altered.

SQL> recover database until cancel;
ORA-00279: change 575876 generated at 12/01/2009 08:19:49 needed for thread 1
ORA-00289: suggestion :
/oracle/flash_recovery_area/ORCL/archivelog/2009_12_01/o1_mf_1_2_%u_.arc
ORA-00280: change 575876 for thread 1 is in sequence #2


Specify log: {=suggested | filename | AUTO | CANCEL}
cancel
Media recovery cancelled.
SQL> alter database open resetlogs;

Database altered.

SQL>

--------------------

ORA-01589: 要打开数据库则必须使用 RESETLOGS 或 NOR


ORA-01589: 要打开数据库则必须使用 RESETLOGS 或 NORESETLOGS
选项


SQL> alter database open 
ORA-01589: 要打开数据库则必须使用 RESETLOGS 或
NORESETLOGS 选项

SQL> alter database open resetlogs;
alter database
open resetlogs
*
ERROR 位于第 1 行:
ORA-01113: 文件 1 需要介质恢复
ORA-01110:
数据文件 1: 'E:\ORACLE\ORADATA\EYGLE\SYSTEM01.DBF'

SQL> recover database
using backup controlfile;
ORA-00279: 更改 1670743 (在 04/17/2008 14:13:16 生成)
对于线程 1 是必需的
ORA-00289: 建议: E:\ORACLE\ORA92\RDBMS\ARC00030.001
ORA-00280:
更改 1670743 对于线程 1 是按序列 # 30 进行的

指定日志: {<RET>=suggested | filename |
AUTO | CANCEL}
E:\oracle\oradata\EYGLE\REDO01.LOG
ORA-00310: 存档日志包含序列
29;要求序列 30
ORA-00334: 归档日志:
'E:\ORACLE\ORADATA\EYGLE\REDO01.LOG'

SQL> recover database using
backup controlfile;
ORA-00279: 更改 1670743 (在 04/17/2008 14:13:16 生成) 对于线程 1
是必需的
ORA-00289: 建议: E:\ORACLE\ORA92\RDBMS\ARC00030.001
ORA-00280: 更改
1670743 对于线程 1 是按序列 # 30 进行的

指定日志: {<RET>=suggested | filename |
AUTO |
CANCEL}
E:\oracle\oradata\EYGLE\REDO02.LOG
已应用的日志。
完成介质恢复。
SQL>
alter database open resetlogs;
数据库已更改。


OK,搞定了!

posted @ 2014-04-30 14:38 brock 阅读(9080) | 评论 (0)编辑 收藏

首先来看问题,然后来看函数的定义,其实什么都在函数定义里面说明白了

1.正则表达式字符串问题

首先输入的regex是一个正则表达式,而不是一个普通的字符串,所以导致很多在正则表达式里面有特殊意义的比如 "." "|" "\" ,如果直接使用是不行的,另外一个方面我们输入的regex是以字符串形式传递的,对有些字符必须要转义,尤其是"\",下面请看例子

String[] aa = "aaa|bbb|ccc".split("|");//wrong
String[] aa = "aaa|bbb|ccc".split("\\|"); //

 

 String[] aa = "aaa*bbb*ccc".split("*");//wrong
 String[] aa = "aaa|bbb|ccc".split("\\*");

 

 String[] aa = "aaa*bbb*ccc".split(".");//wrong
 String[] aa = "aaa|bbb|ccc".split("\\.");

 

String[] aa = "aaa\\bbb\\bccc".split("\\");//wrong

String[] aa = "aaa\\bbb\\bccc".split("\\\\");

 

2.数组长度的问题

String a = "";
String[] b = a.split(",");
b.length为 1;
*
String a = "c";
String[] b = a.split(",");
b.length为 1;
**
String a = "c,,,";
String[] b = a.split(",");
b.length为 1;
***
String a = "c,,c";
String[] b = a.split(",");
b.length为 3;
****
String a = ",";
String[] b = a.split(",");
b.length为 0;

 

其实只要添加一个参数即可,例如

String str = "abcdef,ghijk,lmno,pqrst,,,";       

String[] array = str.split(",");
输出:abcdef,ghijk,lmno,pqrst,

 

String str = "abcdef,ghijk,lmno,pqrst,,,";
String[] array 
= str.split(",",-1);

输出:abcdef,ghijk,lmno,pqrst,,,,

 

public String [] split (String  regex, int limit) 

最后一个参数limit是影响返回数组的长度的

=========================请关注红色字体(括号内为注释)==========================================

public String[] split(String regex)

根据给定的正则表达式的匹配来拆分此字符串。

该方法的作用就像是使用给定的表达式和限制参数 0 来调用两参数 split 方法。因此,结果数组中不包括结尾空字符串(直接使用会造成数组大小问题)

例如,字符串 "boo:and:foo" 产生带有下面这些表达式的结果:

Regex结果
:{ "boo", "and", "foo" }
o{ "b", "", ":and:f" }

 

参数:
regex - 定界正则表达式
返回:
字符串数组,根据给定正则表达式的匹配来拆分此字符串,从而生成此数组。

public String[] split(String regex,
                      int limit)

根据匹配给定的正则表达式来拆分此字符串。

此方法返回的数组包含此字符串的每个子字符串,这些子字符串由另一个匹配给定的表达式的子字符串终止或由字符串结束来终止。数组中的子字符串按它们在此字符串中的顺序排列。如果表达式不匹配输入的任何部分,则结果数组只具有一个元素,即此字符串。

limit 参数控制模式应用的次数,因此影响结果数组的长度如果该限制 n 大于 0,则模式将被最多应用 n - 1 次,数组的长度将不会大于 n,而且数组的最后项将包含超出最后匹配的定界符的所有输入。如果 n 为非正,则模式将被应用尽可能多的次数,而且数组可以是任意长度。如果 n 为零,则模式将被应用尽可能多的次数,数组可有任何长度,并且结尾空字符串将被丢弃

例如,字符串 "boo:and:foo" 使用这些参数可生成下列结果:

RegexLimit结果
:2{ "boo", "and:foo" }
:5{ "boo", "and", "foo" }
:-2{ "boo", "and", "foo" }
o5{ "b", "", ":and:f", "", "" }
o-2{ "b", "", ":and:f", "", "" }
o0{ "b", "", ":and:f" }

这种形式的方法调用 str.split(regex, n) 产生与以下表达式完全相同的结果:

Pattern.compile(regex).split(str, n)

 

参数:
regex - 定界正则表达式
limit - 结果阈值,如上所述
返回:
字符串数组,根据给定正则表达式的匹配来拆分此字符串,从而生成此数组

 

posted @ 2014-04-28 10:15 brock 阅读(238) | 评论 (0)编辑 收藏

  List<Calendar> l = new ArrayList<Calendar>(); 
while (true) {
l.add(Calendar.getInstance());
System.out.println(l.size());
}
605473
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Calendar.<init>(Unknown Source)
at java.util.GregorianCalendar.<init>(Unknown Source)
at java.util.Calendar.createCalendar(Unknown Source)
at java.util.Calendar.getInstance(Unknown Source)
at jodatestmemory.Main.main(Main.java:25)
posted @ 2014-01-08 11:26 brock 阅读(359) | 评论 (0)编辑 收藏

头文件
#ifndef CLASS_GEOMETRYTOSTRING
#define CLASS_GEOMETRYTOSTRING
 
#include <iostream>
#include <FileGDBAPI.h>
using namespace std;
class GeometryToString
{
public:
static  bool getGeometryStr( FileGDBAPI::ShapeBuffer &geometry,string srid,string &geometrystr); 
private:
static void getPointGML(FileGDBAPI::PointShapeBuffer *&pbuffer,string srid,string dimension, string &xml);
static void getLineGML(FileGDBAPI::MultiPartShapeBuffer *&lineGeometry,string srid,string dimension, string &xml);
static void getMultipointGML(FileGDBAPI::MultiPointShapeBuffer *&multipointGeometry,string srid,string dimension, string &xml);
static void getPolygonGML(FileGDBAPI::MultiPartShapeBuffer *&polygonGeometry,string srid,string dimension, string &xml);
};
#endif
--------------------------------
#include <jni.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include <time.h>
#include <sstream> 
#include <FileGDBAPI.h>
#include "GeometryToString.h"
using namespace FileGDBAPI;
using namespace std;
/**
ShapeBuffer geometry format to gml
*/
bool GeometryToString::getGeometryStr( ShapeBuffer &geometry,string srid,string &geometrystr)     
{
ShapeType pType;
string dimension("2");
try{
geometry.GetShapeType(pType);
if(pType==shapeNull){
return false;
}
if(geometry.HasMs(pType) || geometry.HasZs(pType)){
dimension.assign("3");
}
//点
if(pType==shapePoint){
PointShapeBuffer *pPoint = static_cast<PointShapeBuffer*>(&geometry);
getPointGML(pPoint, srid, dimension, geometrystr);
}
//复杂点 shapeMultipoint         =  8, shapeMultipointM        = 28,  shapeMultipointZM       = 18, shapeMultipointZ        = 20,
else if(pType==shapeMultipoint||pType==shapeMultipointZ){
MultiPointShapeBuffer *pPoint = static_cast<MultiPointShapeBuffer*>(&geometry);
getMultipointGML(pPoint, srid, dimension, geometrystr);
}
//线
else if(pType==shapePolyline||pType==shapePolylineZ){
MultiPartShapeBuffer *pPoint = static_cast<MultiPartShapeBuffer*>(&geometry);
getLineGML(pPoint, srid, dimension, geometrystr);
}
//面 shapePolygon            =  5, shapePolygonM           = 25,  shapePolygonZM          = 15,  shapePolygonZ           = 19,
else if(pType==shapePolygon||pType==shapePolygonZ){
MultiPartShapeBuffer *pPoint = static_cast<MultiPartShapeBuffer*>(&geometry);
getPolygonGML(pPoint, srid, dimension, geometrystr);
}
//geometrystr = xml;
}catch(exception& e){
cout <<"格式化gml出错"<< e.what() << '\n';
return false;
}
return true;
}
/**
<gml:Polygon srsName="SDO:4269" xmlns:gml="http://www.opengis.net/gml">
<gml:exterior>
<gml:LinearRing>
<gml:posList srsDimension="2">-73.2580598287651 42.7460586400617 -73.0196951738303 42.740396678634 -72.9229974292253 42.7373644761786 -72.4557700038866 42.7258525290856 -72.4621713056891 42.7468405310805 -72.4793225257782 42.7615879021406 -72.507269529053 42.768732690401 -72.513068008801 42.7892594013537 -72.5389169708409 42.8077338159122 -72.5534284639708 42.8606431711071 -72.5248100213574 42.912614176111 -72.5202170578447 42.951672527189 -72.5042636319544 42.9655846501007 -72.4733411974969 42.9761435837694 -72.4571590376321 42.9996036974295 -72.461752087004 43.0465044640799 -72.4434642578885 43.0790393128302 -72.4376049020671 43.1162700005077 -72.4523985528512 43.1560221784821 -72.4355986440692 43.2322535514026 -72.4024188454006 43.3073827061476 -72.4102315830492 43.3234041461304 -72.3976280543775 43.3510068532968 -72.4121395531362 43.3771255999364 -72.3962478080998 43.4101565518933 -72.3825156946812 43.4846296935806 -72.3949977682121 43.5175538931663 -72.3734983899535 43.5723746289273 -72.3330851941569 43.597364792188 -72.3040399378543 43.6985301192074 -72.2600555952028 43.7353001230665 -72.219122921336 43.7506925284353 -72.2060918209679 43.7646350589214 -72.1848363730122 43.80169046066 -72.1700895247441 43.8789176964692 -72.1216496397887 43.9092173247051 -72.1132040793556 43.9391659598858 -72.0917117306645 43.9579911279466 -72.1128078470402 43.9765149671878 -72.109908766997 43.9892291134735 -72.0852043813773 44.0089239861752 -72.0769190441221 44.0320405986229 -72.0347283650035 44.0833740182692 -72.0324473746587 44.0960996192242 -72.0495148341973 44.1004520944913 -72.034919852375 44.1207459288225 -72.0447245537617 44.1564355666161 -72.0592822460624 44.1821766291117 -72.0443903804218 44.2343798441307 -72.0595660047421 44.2614940911533 -72.0354953753776 44.2994343131499 -71.9944335108703 44.327548202346 -71.9389056579791 44.3257860034125 -71.9283617527138 44.3361121851129 -71.8348159803514 44.3441994129005 -71.821197308355 44.3503600453548 -71.7977291908463 44.3841728130012 -71.7665702593917 44.3982488046659 -71.6768843632127 44.4213427403399 -71.6563990024127 44.4401373612433 -71.6477091613881 44.4691741459765 -71.6365547217831 44.4767309013869 -71.6142227691161 44.4745070427354 -71.5866189807601 44.4945375694191 -71.5752435447921 44.5258056891543 -71.5914413886211 44.5388744007984 -71.5922884113102 44.5512031068491 -71.5367908177936 44.578931263059 -71.554102635183 44.5965889130363 -71.5680271516494 44.6374468081651 -71.588749347522 44.6505994869911 -71.6076787297883 44.6778622938611 -71.6311328527304 44.741710760694 -71.583501209059 44.779196995866 -71.5751009123659 44.8160197976273 -71.5063649605901 44.8996711859762 -71.5169776077168 44.9436961331566 -71.5409270967342 44.9765632062274 -71.5053723006288 45.0133517163227 -71.9018687560566 45.0073398737601 -72.547231170846 45.0053701041526 -73.1885457846918 45.0084861445147 -73.3447234868808 45.0061387945908 -73.3507583871194 44.9819729513452 -73.336414678892 44.9326039308501 -73.3823067594393 44.847933618761 -73.3690541280725 44.8191179021752 -73.3267863194035 44.7992935709543 -73.3731585750219 44.7242364367472 -73.3581509561493 44.6803685644813 -73.3730971364166 44.661276356252 -73.3701366913554 44.6343490646186 -73.3818251037205 44.619807725515 -73.3712960298211 44.5791669569445 -73.3478119840265 44.5539715457203 -73.3344524939974 44.5443282463014 -73.2933197444992 44.4328535783628 -73.2999951630005 44.4055331645411 -73.329788093029 44.3673904680867 -73.3053256664728 44.2601422576288 -73.3773326255291 44.2012475171298 -73.3820623364064 44.1721076120789 -73.4078648304615 44.1362270392698 -73.408756830709 44.1066103535608 -73.4352152780239 44.0638978024284 -73.4360007112789 44.0456791904392 -73.4082513023357 44.0182219013789 -73.4174061301201 43.9881969457531 -73.4053345287368 43.9148075869024 -73.3751207851313 43.8859769501208 -73.3847399017653 43.8045079717314 -73.35899716813 43.7784275686935 -73.3566696765928 43.7565583405993 -73.3709893845573 43.7142811167279 -73.4229598542952 43.6321147289768 -73.4183198417113 43.5824793859982 -73.38811421923 43.569143658301 -73.3636855615672 43.6149988679746 -73.303534516911 43.6247148128503 -73.2941043006646 43.6196528756939 -73.2817362682322 43.593187249577 -73.2914024969012 43.5750335705379 -73.2599837938072 43.5593823395161 -73.2383913589494 43.5128328494146 -73.2500714436228 43.3108539907423 -73.2760052890117 42.9402941192892 -73.2795831999318 42.8371033274803 -73.2961697572314 42.8035493647592 -73.2692753169001 42.7474814329983 -73.2580598287651 42.7460586400617 </gml:posList>
</gml:LinearRing>
</gml:exterior>
</gml:Polygon>
-----------------------------------------
<gml:MultiSurface srsName="SDO:4269" xmlns:gml="http://www.opengis.net/gml">
<gml:surfaceMember>
<gml:Polygon>
<gml:exterior>
<gml:LinearRing>
<gml:posList srsDimension="2">-71.7901942031213 41.6013068793251 -71.8027434308056 41.415829054006 -71.8459956537022 41.403854541649 -71.8368696812943 41.3419614666217 -71.8477722040922 41.3253484832966 -71.866678442895 41.3227696452717 -71.7222643227053 41.327264312184 -71.4898880400564 41.3920853196253 -71.427318519639 41.4866893796324 -71.4192468515382 41.6522122329241 -71.3690125475301 41.7032911019032 -71.3935805976545 41.7611558353254 -71.3673874451962 41.7413502009834 -71.2840016520154 41.6795489704365 -71.2289761591777 41.7076939683675 -71.2666285816006 41.7497430522049 -71.3193277902704 41.7721958646079 -71.33979862314 41.784425562696 -71.3454831662469 41.8131613833438 -71.3345427095385 41.8579036075386 -71.3424931202155 41.875782891498 -71.3330859502879 41.8960311596525 -71.3839531547034 41.8884397544728 -71.3824052822434 41.9792630768654 -71.3786442228911 42.0137133195164 -71.4974303691298 42.0092535031424 -71.7978316087618 42.0042748046853 -71.7882488621949 41.721603395324 -71.7926052182918 41.6417579304639 -71.7901942031213 41.6013068793251 </gml:posList>
</gml:LinearRing>
</gml:exterior>
</gml:Polygon>
</gml:surfaceMember>
<gml:surfaceMember>
<gml:Polygon>
<gml:exterior>
<gml:LinearRing>
<gml:posList srsDimension="2">-71.1988086806703 41.6785003452844 -71.1999371652607 41.4633184834308 -71.1171327154704 41.4930619563069 -71.1412126344661 41.6552730544526 -71.1988086806703 41.6785003452844 </gml:posList>
</gml:LinearRing>
</gml:exterior>
</gml:Polygon>
</gml:surfaceMember>
<gml:surfaceMember>
<gml:Polygon>
<gml:exterior>
<gml:LinearRing>
<gml:posList srsDimension="2">-71.2691694549114 41.6212683171835 -71.3495250332551 41.445857741455 -71.288007152861 41.4836193369167 -71.2386732340455 41.4748497781273 -71.2194468005559 41.6356423127122 -71.2691694549114 41.6212683171835 </gml:posList>
</gml:LinearRing>
</gml:exterior>
</gml:Polygon>
</gml:surfaceMember>
</gml:MultiSurface>
*/
void GeometryToString::getPolygonGML(FileGDBAPI::MultiPartShapeBuffer *&polygonGeometry,string srid,string dimension, string &xml){
int numPts;
polygonGeometry->GetNumPoints(numPts);
int numParts;
polygonGeometry->GetNumParts(numParts);
int* parts;
polygonGeometry->GetParts(parts);
Point* points;
polygonGeometry->GetPoints(points);
string gmlSub("");
if(numParts==1){
xml= "<gml:Polygon srsName=\"SDO:"+srid+"\" xmlns:gml=\"http://www.opengis.net/gml\"> \
<gml:exterior> \
<gml:LinearRing> \
<gml:posList srsDimension=\""+dimension+"\">";
for (int i = 0; i < numPts; i++)
{
char buffer[32];
sprintf(buffer, "%1.14g", points[i].x);
gmlSub.append(buffer).append(" ");
sprintf(buffer, "%1.14g", points[i].y);
gmlSub.append(buffer).append(" ");
}  
xml.append(gmlSub);
xml.append("</gml:posList></gml:LinearRing>\
  </gml:exterior>\
  </gml:Polygon>");
return;
}
if(numParts>1){
xml="<gml:MultiSurface srsName=\"SDO:"+srid+"\" xmlns:gml=\"http://www.opengis.net/gml\">";
for(int i=0;i<numParts;i++){
gmlSub.append("<gml:surfaceMember>\
 <gml:Polygon>\
 <gml:exterior>\
 <gml:LinearRing>\
 <gml:posList srsDimension=\"").append(dimension).append("\">");
int gt=0;
if( i==(numParts-1)){
gt=numPts;
}else{
gt=parts[i+1];
}
for (int j= parts[i]; j < gt; j++){
char buffer[32];
sprintf(buffer, "%1.14g", points[j].x);
gmlSub.append(buffer).append(" ");
sprintf(buffer, "%1.14g", points[j].y);
gmlSub.append(buffer).append(" ");
}
gmlSub.append("</gml:posList>\
 </gml:LinearRing>\
 </gml:exterior>\
 </gml:Polygon>\
 </gml:surfaceMember>");
}
xml.append(gmlSub);
xml.append("</gml:MultiSurface>");
return;
}
}
/**
<gml:MultiPoint srsName="SDO:2230" xmlns:gml="http://www.opengis.net/gml">
<gml:pointMember>
<gml:Point>
<gml:posList srsDimension="3">6301153.87493073 1913012.75794829 435.0 </gml:posList>
</gml:Point>
</gml:pointMember>
<gml:pointMember>
<gml:Point>
<gml:posList srsDimension="3">6301172.62522131 1913331.50796697 424.0 </gml:posList>
</gml:Point>
</gml:pointMember>
</gml:MultiPoint>
*/
void GeometryToString::getMultipointGML(FileGDBAPI::MultiPointShapeBuffer *&multipointGeometry,string srid,string dimension, string &xml){
int numPts;
multipointGeometry->GetNumPoints(numPts);
wcout << "Multipoint test:" << endl;
wcout << "Points: " << numPts << endl;
Point* points;
multipointGeometry->GetPoints(points);
double* zArray;
multipointGeometry->GetZs(zArray);
xml= "<gml:MultiPoint srsName=\"SDO:"+srid+"\" xmlns:gml=\"http://www.opengis.net/gml\"> ";
string gmlSub("");
for (int i = 0; i < numPts; i++)
{
gmlSub.append("<gml:pointMember><gml:Point><gml:posList srsDimension=\""+dimension+"\">");
char buffer[32];
sprintf(buffer, "%1.14g", points[i].x);
gmlSub.append(buffer).append(" ");
sprintf(buffer, "%1.14g", points[i].y);
gmlSub.append(buffer).append(" ");
sprintf(buffer, "%1.14g", zArray[i]);
gmlSub.append(buffer).append(" ");
gmlSub.append("</gml:posList></gml:Point></gml:pointMember>");
}
xml.append(gmlSub);
xml.append("</gml:MultiPoint>");
}
/**
<gml:Curve srsName="SDO:4269" xmlns:gml="http://www.opengis.net/gml">
<gml:segments>
<gml:LineStringSegment>
<gml:posList srsDimension="2">-91.3082592401631 40.0073363232732 -91.3055891069314 39.995346341049 -91.3139124547158 39.9690362798168 -91.3254189367963 39.9469572142013 -91.3246098997585 39.9350861975012 -91.32260281264 39.9251371873939 -91.3238158572038 39.896847138931 -91.3220157795743 39.8891571322064 -91.3241598689896 39.8853761196319 -91.3383584637069 39.873997056967 -91.3394875098243 39.8690760451917 -91.3354593387828 39.8630950480564 -91.3031399738825 39.8280070993682 -91.3022619338156 39.8090860744066 -91.2985697775187 39.7987370721841 -91.3005688605598 39.7949870596141 -91.3073361425165 39.7886050259611 -91.3117993281738 39.783596002295 -91.3119823326406 39.7676969773468 -91.3108232836762 39.7648359772821 -91.3049330369361 39.7602849923819 -91.2990957929273 39.7579610108158 -91.1947826970924 39.7164273102698 </gml:posList>
</gml:LineStringSegment>
</gml:segments>
</gml:Curve>
<gml:MultiCurve srsName="SDO:4269" xmlns:gml="http://www.opengis.net/gml">
<gml:curveMember>
<gml:Curve>
<gml:segments>
<gml:LineStringSegment>
<gml:posList srsDimension="2"> sssss</gml:posList>
</gml:LineStringSegment>
</gml:segments>
</gml:Curve>
</gml:curveMember>
<gml:curveMember>
<gml:Curve>
<gml:segments>
<gml:LineStringSegment>
<gml:posList srsDimension="2">sssss </gml:posList>
</gml:LineStringSegment>
</gml:segments>
</gml:Curve>
</gml:curveMember>
</gml:MultiCurve>
*/
void GeometryToString::getLineGML(MultiPartShapeBuffer *&lineGeometry,string srid,string dimension, string &xml)
{
int numPts,numParts;
lineGeometry->GetNumPoints(numPts);
lineGeometry->GetNumParts(numParts);
int* parts;
lineGeometry->GetParts(parts);
Point* points;
lineGeometry->GetPoints(points);
string gmlSub("");
if(numParts==1){
xml= "<gml:Curve srsName=\"SDO:"+srid+"\" xmlns:gml=\"http://www.opengis.net/gml\"> \
 <gml:segments> \
 <gml:LineStringSegment> \
 <gml:posList srsDimension=\""+dimension+"\">";
for (int i = 0; i < numPts; i++)
{
char buffer[32];
sprintf(buffer, "%1.14g", points[i].x);
gmlSub.append(buffer).append(" ");
sprintf(buffer, "%1.14g", points[i].y);
gmlSub.append(buffer).append(" ");
}  
xml.append(gmlSub);
xml.append("</gml:posList> \
  </gml:LineStringSegment>\
  </gml:segments> \
  </gml:Curve>");
return;
}
if(numParts>1){
xml="<gml:MultiCurve srsName=\"SDO:"+srid+"\" xmlns:gml=\"http://www.opengis.net/gml\">";
for(int i=0;i<numParts;i++){
gmlSub.append("<gml:curveMember>\
 <gml:Curve>\
 <gml:segments>\
 <gml:LineStringSegment>\
 <gml:posList srsDimension=\"").append(dimension).append("\">");
int gt=0;
if( i==(numParts-1)){
gt=numPts;
}else{
gt=parts[i+1];
}
for (int j= parts[i]; j < gt; j++){
char buffer[32];
sprintf(buffer, "%1.14g", points[j].x);
gmlSub.append(buffer).append(" ");
sprintf(buffer, "%1.14g", points[j].y);
gmlSub.append(buffer).append(" ");
}
gmlSub.append("</gml:posList>\
 </gml:LineStringSegment>\
 </gml:segments>\
 </gml:Curve>\
 </gml:curveMember>");
}
xml.append(gmlSub);
xml.append("</gml:MultiCurve>");
return;
}
}
/*
<gml:Point srsName="SDO:4269" xmlns:gml="http://www.opengis.net/gml">
<gml:posList srsDimension="2">-88.0261499418109 44.4722440557492 </gml:posList>
</gml:Point>
*/
void GeometryToString::getPointGML( PointShapeBuffer *&pbuffer,string srid,string dimension, string &xml)
{
xml= "<gml:Point srsName=\"SDO:"+srid+"\" xmlns:gml=\"http://www.opengis.net/gml\"><gml:posList srsDimension=\""+dimension+"\">";
Point* points;
pbuffer->GetPoint(points);
char buffer[32];
sprintf(buffer, "%1.14g", points[0].x);
xml.append(buffer).append(" ");
sprintf(buffer, "%1.14g", points[0].y);
xml.append(buffer).append(" ");
xml.append("</gml:posList></gml:Point>");
}
posted @ 2014-01-02 10:19 brock 阅读(326) | 评论 (0)编辑 收藏

写给自己看看
java --HelloJNI ---
import java.io.UnsupportedEncodingException;
public class HelloJNI {
static {
     System.loadLibrary("HelloJNI"); // hello.dll (Windows) or libhello.so (Unixes)
  
  }
  // A native method that receives nothing and returns void
  private native void sayHello();
  
  private native double sayOK(String dd);
  
  private native void getFileGdb(String path);
  
  private native String getFileGdbStr(String path);
  
  private native GeodbEntity getGdbTable(GeodbEntity geo);
 
  /**
* @param args
* @throws UnsupportedEncodingException
*/
/**  
* @param args
* @throws UnsupportedEncodingException
*/
public static void main(String[] args) throws UnsupportedEncodingException {
//   System.out.println( System.getProperty("java.library.path"));
  HelloJNI hello =  new HelloJNI();
//   hello.sayHello();  // invoke the native method
  
//   System.out.println(hello.sayOK("Apple"));
//   
  //hello.getFileGdb("D:/cpp/FileGDB_API_VS2012_1_3/samples/data/ExecuteSQL.gdb");
  //GeodbEntity dd= hello.getGdbTable("D:/cpp/FileGDB_API_VS2012_1_3/samples/data/ExecuteSQL.gdb","dd");
  GeodbEntity dd= new GeodbEntity();
  dd.setTable("D:/cpp/FileGDB_API_VS2012_1_3/samples/data/ExecuteSQL.gdb 阿切尔");
  
  hello.getGdbTable(dd);
 
 System.out.println("java"+dd.getSrid());
 for(int i=0;i<dd.getFieldValues().size();i++){
 System.out.println(dd.getFieldValues().get(i));
 
 }
 // System.out.println(hello.getFileGdbStr("D:/cpp/FileGDB_API_VS2012_1_3/samples/data/ExecuteSQL.gdb"));
  
  }
}
-----GeodbEntity ----
import java.util.List;
import java.util.ArrayList;
public class GeodbEntity {
//输入
private String table;
private String eodbPath;
//输出
/**列字段##隔开*/
private String Fields;
/**数据表##隔开*/
private ArrayList<String> FieldValues=new ArrayList<String>();
/**空间参考标识符*/
private String srid;
/**维度*/
private String dimension;
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public String getEodbPath() {
return eodbPath;
}
public void setEodbPath(String eodbPath) {
this.eodbPath = eodbPath;
}
public String getSrid() {
return srid;
}
public void setSrid(String srid) {
this.srid = srid;
}
public String getDimension() {
return dimension;
}
public void setDimension(String dimension) {
this.dimension = dimension;
}
public String getFields() {
return Fields;
}
public void setFields(String fields) {
Fields = fields;
}
public ArrayList<String> getFieldValues() {
return FieldValues;
}
public void setFieldValues(ArrayList<String> fieldValues) {
FieldValues = fieldValues;
}
public String toString() {
        return Fields;
    }
}
--c++
hellojni.h
#define _Included_HelloJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloJNI
 * Method:    sayHello
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloJNI_sayHello
  (JNIEnv *, jobject);
/*
 * Class:     HelloJNI
 * Method:    sayOK
 * Signature: (Ljava/lang/String;)D
 */
JNIEXPORT jdouble JNICALL Java_HelloJNI_sayOK
  (JNIEnv *, jobject, jstring);
/*
 * Class:     HelloJNI
 * Method:    getFileGdb
 * Signature: (Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_HelloJNI_getFileGdb
  (JNIEnv *, jobject, jstring);
/*
 * Class:     HelloJNI
 * Method:    getFileGdbStr
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_HelloJNI_getFileGdbStr
  (JNIEnv *, jobject, jstring);
/*
 * Class:     HelloJNI
 * Method:    getGdbTable
 * Signature: (LGeodbEntity;)LGeodbEntity;
 */
JNIEXPORT jobject JNICALL Java_HelloJNI_getGdbTable
  (JNIEnv *, jobject, jobject);
#ifdef __cplusplus
}
#endif
#endif
----------hello c++------

#include <jni.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include "HelloJNI.h"
#include <fstream>
#include <time.h>
#include <FileGDBAPI.h>
using namespace std;
using namespace FileGDBAPI;
using namespace std;
 
JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) {
printf("Hello World!\n");
return;
}
JNIEXPORT jdouble JNICALL Java_HelloJNI_sayOK
(JNIEnv* env, jobject obj, jstring name){
const char* pname=env->GetStringUTFChars(name,NULL);
if(strcmp(pname,"Apple")==0){
env->ReleaseStringUTFChars(name,pname);
cout<<"After release:"<<pname<<endl;
return 1.2;
}
else{
env->ReleaseStringUTFChars(name,pname);
cout<<"After release:"<<pname<<endl;
return 2.1;
}
}
JNIEXPORT jstring JNICALL Java_HelloJNI_getFileGdbStr
(JNIEnv *env, jobject thisObj, jstring path){
/* fgdbError hr;
wstring errorText;
Geodatabase geodatabase;
std::wstring value;
const jchar* raw = env->GetStringChars(path, NULL);
if (raw != NULL) {
jsize len = env->GetStringLength(path);
value.assign(raw, raw + len);
env->ReleaseStringChars(path, raw);
}
if ((hr = OpenGeodatabase(value, geodatabase)) != S_OK)
{
wcout << "An error occurred while opening the geodatabase." << endl;
ErrorInfo::GetErrorDescription(hr, errorText);
wcout << errorText << "(" << hr << ")." << endl;
return (env)->NewStringUTF("7");
}
Row     attrQueryRow;
EnumRows attrQueryRows;
wstring sqlStatement(L"SELECT * FROM Cities WHERE TYPE = 'city' AND OBJECTID < 10");
if ((hr = geodatabase.ExecuteSQL(sqlStatement, true, attrQueryRows)) != S_OK)
{
wcout << "An error occurred while performing the attribute query." << endl;
ErrorInfo::GetErrorDescription(hr, errorText);
wcout << errorText << "(" << hr << ")." << endl;
return (env)->NewStringUTF("7");
}
FieldInfo fieldInfo;
attrQueryRows.GetFieldInformation(fieldInfo);
int       fieldCount;
FieldType fieldType;
wstring   fieldName;
// Iterate through the returned rows printing out all field values.
short     shortField;
int32     longField;
float     floatField;
double    doubleField;
string    stringField;
wstring   wstringField;
tm        dateTimeField;
char      datetime[80];
Guid      globalIDField;
Guid      guidField;
wstring   strGuid;
wstring   strGlobalID;
bool      isNull;
byte * shapeBufferBytes ;
ShapeBuffer geometry;
ByteArray  bss;
while (attrQueryRows.Next(attrQueryRow) == S_OK)
{
fieldInfo.GetFieldCount(fieldCount);
for (long fieldNumber = 0; fieldNumber < fieldCount; fieldNumber++)
{
fieldInfo.GetFieldType(fieldNumber, fieldType);
fieldInfo.GetFieldName(fieldNumber, fieldName);
attrQueryRow.IsNull(fieldName, isNull);
if (!isNull)
{
switch (fieldType)
{
case fieldTypeSmallInteger:
attrQueryRow.GetShort(fieldName, shortField);
wcout <<  shortField << endl;
break;
case fieldTypeInteger:
attrQueryRow.GetInteger(fieldName, longField);
wcout << longField << '\t';
break;
case fieldTypeSingle:
attrQueryRow.GetFloat(fieldName, floatField);
wcout << floatField << '\t';
break;
case fieldTypeDouble:
attrQueryRow.GetDouble(fieldName, doubleField);
wcout << doubleField << '\t';
break;
case fieldTypeString:
attrQueryRow.GetString(fieldName, wstringField);
wcout << wstringField << '\t';
break;
case fieldTypeDate:
attrQueryRow.GetDate(fieldName, dateTimeField);
strftime(datetime,80,"%a %b %d %I:%M:%S%p %Y", &dateTimeField);
wcout << datetime << '\t';
break;
case fieldTypeOID:
attrQueryRow.GetOID(longField);
wcout << longField << '\t';
break;
case fieldTypeGeometry:{
attrQueryRow.GetGeometry(geometry);
// attrQueryRow.GetBinary(fieldName, bss);
double x, y;
shapeBufferBytes = geometry.shapeBuffer;
wcout << "d::x::"<< x<<"y:"<<y<< '\t';;
wcout <<shapeBufferBytes<< "Geometry" << '\t';}
break;
case fieldTypeBlob:
wcout << "Blob" << '\t';
break;
case fieldTypeGUID:
attrQueryRow.GetGUID(fieldName, guidField);
guidField.ToString(strGuid);
wcout << strGuid << '\t';
break;
case fieldTypeGlobalID:
attrQueryRow.GetGlobalID(globalIDField);
globalIDField.ToString(strGlobalID);
wcout << strGlobalID << '\t';
break;
default:
break;
}
}
else
{
wcout << "null" << '\t';
}
}
wcout << endl;
}
attrQueryRows.Close(); // Close the EnumRows
*/
const char * pat="zhy好棒呀 第一个东东出来了";
//定义java String类 strClass  
jclass strClass = (env)->FindClass("Ljava/lang/String;");  
//获取String(byte[],String)的构造器,用于将本地byte[]数组转换为一个新String  
jmethodID ctorID = (env)->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");  
//建立byte数组  
jbyteArray bytes = (env)->NewByteArray(strlen(pat));  
//将char* 转换为byte数组  
(env)->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte*)pat);  
// 设置String, 保存语言类型,用于byte数组转换至String时的参数  
jstring encoding = (env)->NewStringUTF("GB2312");   
//将byte数组转换为java String,并输出  
return (jstring)(env)->NewObject(strClass, ctorID, bytes, encoding);  
//return path;
}
JNIEXPORT void JNICALL Java_HelloJNI_getFileGdb(JNIEnv *env, jobject thisObj, jstring path) {
fgdbError hr;
wstring errorText;
Geodatabase geodatabase;
// const wchar_t * szStr =(wchar_t * )env->GetStringChars(path, NULL);
std::wstring value;
const jchar* raw = env->GetStringChars(path, NULL);
if (raw != NULL) {
jsize len = env->GetStringLength(path);
value.assign(raw, raw + len);
env->ReleaseStringChars(path, raw);
}
if ((hr = OpenGeodatabase(value, geodatabase)) != S_OK)
{
wcout << "An error occurred while opening the geodatabase." << endl;
ErrorInfo::GetErrorDescription(hr, errorText);
wcout << errorText << "(" << hr << ")." << endl;
return;
}
wstring sqlStatement(L"SELECT CITY_NAME, POP1990 FROM Cities WHERE TYPE = 'city' AND OBJECTID < 10");
EnumRows attrQueryRows;
if ((hr = geodatabase.ExecuteSQL(sqlStatement, true, attrQueryRows)) != S_OK)
{
wcout << "An error occurred while performing the attribute query." << endl;
ErrorInfo::GetErrorDescription(hr, errorText);
wcout << errorText << "(" << hr << ")." << endl;
return ;
}
// Iterate through the returned rows.
Row     attrQueryRow;
int32   cityPop;
wstring cityName;
while (attrQueryRows.Next(attrQueryRow) == S_OK)
{
attrQueryRow.GetInteger(L"POP1990", cityPop);
attrQueryRow.GetString(L"CITY_NAME", cityName);
wcout << cityName << '\t' << cityPop << endl;
}
// SELECT * - Return all fields.
sqlStatement.assign(L"SELECT * FROM Cities WHERE TYPE = 'city' AND OBJECTID < 10");
if ((hr = geodatabase.ExecuteSQL(sqlStatement, true, attrQueryRows)) != S_OK)
{
wcout << "An error occurred while performing the attribute query." << endl;
ErrorInfo::GetErrorDescription(hr, errorText);
wcout << errorText << "(" << hr << ")." << endl;
return;
}
// Get the field type and name from the row enumerator.
FieldInfo fieldInfo;
attrQueryRows.GetFieldInformation(fieldInfo);
int       fieldCount;
FieldType fieldType;
wstring   fieldName;
// Iterate through the returned rows printing out all field values.
short     shortField;
int32     longField;
float     floatField;
double    doubleField;
string    stringField;
wstring   wstringField;
tm        dateTimeField;
char      datetime[80];
Guid      globalIDField;
Guid      guidField;
wstring   strGuid;
wstring   strGlobalID;
bool      isNull;
byte * shapeBufferBytes ;
ShapeBuffer geometry;
while (attrQueryRows.Next(attrQueryRow) == S_OK)
{
fieldInfo.GetFieldCount(fieldCount);
for (long fieldNumber = 0; fieldNumber < fieldCount; fieldNumber++)
{
fieldInfo.GetFieldType(fieldNumber, fieldType);
fieldInfo.GetFieldName(fieldNumber, fieldName);
attrQueryRow.IsNull(fieldName, isNull);
if (!isNull)
{
switch (fieldType)
{
case fieldTypeSmallInteger:
attrQueryRow.GetShort(fieldName, shortField);
wcout <<  shortField << endl;
break;
case fieldTypeInteger:
attrQueryRow.GetInteger(fieldName, longField);
wcout << longField << '\t';
break;
case fieldTypeSingle:
attrQueryRow.GetFloat(fieldName, floatField);
wcout << floatField << '\t';
break;
case fieldTypeDouble:
attrQueryRow.GetDouble(fieldName, doubleField);
wcout << doubleField << '\t';
break;
case fieldTypeString:
attrQueryRow.GetString(fieldName, wstringField);
wcout << wstringField << '\t';
break;
case fieldTypeDate:
attrQueryRow.GetDate(fieldName, dateTimeField);
strftime(datetime,80,"%a %b %d %I:%M:%S%p %Y", &dateTimeField);
wcout << datetime << '\t';
break;
case fieldTypeOID:
attrQueryRow.GetOID(longField);
wcout << longField << '\t';
break;
case fieldTypeGeometry:{
attrQueryRow.GetGeometry(geometry);
// attrQueryRow.GetBinary(fieldName, bss);
double x, y;
shapeBufferBytes = geometry.shapeBuffer;
memcpy(&x, geometry.shapeBuffer + 4, sizeof(x));
memcpy(&y, geometry.shapeBuffer + 12, sizeof(y));
//std::string *str3 = new std::string((char *)shapeBufferBytes);
wcout << "d::x::"<< x<<"y:"<<y<< '\t';;
wcout <<shapeBufferBytes<< "Geometry" << '\t';}
  break;
case fieldTypeBlob:
wcout << "Blob" << '\t';
break;
case fieldTypeGUID:
attrQueryRow.GetGUID(fieldName, guidField);
guidField.ToString(strGuid);
wcout << strGuid << '\t';
break;
case fieldTypeGlobalID:
attrQueryRow.GetGlobalID(globalIDField);
globalIDField.ToString(strGlobalID);
wcout << strGlobalID << '\t';
break;
default:
break;
}
}
else
{
wcout << "null" << '\t';
}
}
wcout << endl;
}
attrQueryRows.Close(); // Close the EnumRows
// Close the geodatabase
if ((hr = CloseGeodatabase(geodatabase)) != S_OK)
{
wcout << "An error occurred while closing the geodatabase." << endl;
ErrorInfo::GetErrorDescription(hr, errorText);
wcout << errorText << "(" << hr << ")." << endl;
return ;
}
printf("Hello World  geodatebase!\n");
return;
}
std::string jstring2str(JNIEnv* env, jstring jstr)  
{     
    char*   rtn   =   NULL;     
    jclass   clsstring   =   env->FindClass("java/lang/String");     
    jstring   strencode   =   env->NewStringUTF("GB2312");     
    jmethodID   mid   =   env->GetMethodID(clsstring,   "getBytes",   "(Ljava/lang/String;)[B");     
    jbyteArray   barr=   (jbyteArray)env->CallObjectMethod(jstr,mid,strencode);     
    jsize   alen   =   env->GetArrayLength(barr);     
    jbyte*   ba   =   env->GetByteArrayElements(barr,JNI_FALSE);     
    if(alen   >   0)     
    {     
        rtn   =   (char*)malloc(alen+1);           
        memcpy(rtn,ba,alen);     
        rtn[alen]=0;     
    }     
    env->ReleaseByteArrayElements(barr,ba,0);     
    std::string stemp(rtn);  
    free(rtn);  
    return   stemp;     
}  
jstring str2jstring(JNIEnv* env,const char* pat)  
{  
    //定义java String类 strClass  
    jclass strClass = (env)->FindClass("Ljava/lang/String;");  
    //获取String(byte[],String)的构造器,用于将本地byte[]数组转换为一个新String  
    jmethodID ctorID = (env)->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");  
    //建立byte数组  
    jbyteArray bytes = (env)->NewByteArray(strlen(pat));  
    //将char* 转换为byte数组  
    (env)->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte*)pat);  
    // 设置String, 保存语言类型,用于byte数组转换至String时的参数  
    jstring encoding = (env)->NewStringUTF("GB2312");   
    //将byte数组转换为java String,并输出  
    return (jstring)(env)->NewObject(strClass, ctorID, bytes, encoding);  
}  
JNIEXPORT jobject JNICALL Java_HelloJNI_getGdbTable(JNIEnv *env, jobject obj,jobject _GeodbEntity){
const char * dd="4096";
//jclass userClass = env->FindClass("GeodbEntity");  
jclass userClass=env->GetObjectClass(_GeodbEntity); 
//jmethodID userMethod = env->GetMethodID(userClass,"<init>","()V"); 
//jobject userObject = env->NewObject(userClass,userMethod);  
//jmethodID construction_id = env->GetMethodID(userClass, "<init>", "()V"); 
//得到构造方法的ID
    //jobject userObject = env->NewObject(userClass, construction_id); 
//jobject   userObject = env->AllocObject(userClass);     
//
//jmethodID setName_method=env->GetMethodID(userClass,"setSrid","(Ljava/lang/String;)V");
//env->CallVoidMethod(userObject,setName_method,dd);
   //jclass objectClass = (env)->FindClass("GeodbEntity
     jmethodID methodId=env->GetMethodID(userClass,"getTable","()Ljava/lang/String;");
 //调用customer对象的特定方法getName
       jstring js_name=(jstring)env->CallObjectMethod(_GeodbEntity,methodId,NULL);
   //jfieldID table = (env)->GetFieldID(userClass,"table","Ljava/lang/String;");
//jchar dd=(env)->GetCharField(userClass,table);
   //std::string value;
//const jchar* raw = env->GetStringChars(js_name, NULL);
//if (raw != NULL) {
//jsize len = env->GetStringLength(js_name);
//value.assign(raw, raw + len);
//env->ReleaseStringChars(js_name, raw);
//}
cout<<jstring2str(env,js_name)<<endl;
   jfieldID str = (env)->GetFieldID(userClass,"srid","Ljava/lang/String;");
  (env)->SetObjectField(_GeodbEntity,str,(env)->NewStringUTF(dd));
   //获取arraylist 类
   jclass cls_ArrayList = env->FindClass("java/util/ArrayList");
//获得arraylist id
        jmethodID construct = env->GetMethodID(cls_ArrayList,"<init>","()V");  
//创建arraylist
        jobject obj_ArrayList = env->NewObject(cls_ArrayList,construct); 
//获取 arraylist 的add 方法
        jmethodID arrayList_add = env->GetMethodID(cls_ArrayList,"add","(Ljava/lang/Object;)Z");  
for(int i=0;i<10;i++){
jobject alistadd = (env)->NewStringUTF("my name is D:"+i); 
//通过 add 方法 添加数据到 arraylist中
env->CallObjectMethod(obj_ArrayList,arrayList_add,alistadd);  
}
jfieldID str1 = (env)->GetFieldID(userClass,"FieldValues","Ljava/util/ArrayList;");
  (env)->SetObjectField(_GeodbEntity,str1,obj_ArrayList);
return _GeodbEntity;
}



posted @ 2013-12-30 14:18 brock 阅读(215) | 评论 (0)编辑 收藏

-环境的搭建,下载与安装LIBXML2和ICONV

          Libxml2是一个C语言的XML程序库,可以简单方便的提供对XML文档的各种操作,并且支持XPATH查询,以及部分的支持XSLT转换等功能。Libxml2的下载地址是http://xmlsoft.org/downloads.html,完全版的库是开源的,并且带有例子程序和说明文档。完全版的文件名为:libxml2-2.7.8.tar.gz。

          Libxml2中默认的内码是UTF-8,所有使用libxml2进行处理的xml文件,必须首先显式或者默认的转换为UTF-8编码才能被处理。
要在xml中使用中文,就必须能够在UTF-8和GB2312内码(较常用的一种简体中文编码)之间进行转换。Libxml2提供了默认的内码转换机制,并且在libxml2的Tutorial中有一个例子,事实证明这个例子并不适合用来转换中文。所以需要我们显式的使用ICONV来进行内码转换,libxml2本身也是ICONV使用进行转换的。ICONV是一个专门用来进行编码转换的库,基本上支持目前所有常用的编码。它是glibc库的一个部分,常常被用于UNIX系统中。当然,在windows下面使用也没有任何问题。

其下载地址是http://gnuwin32.sourceforge.net/packages/libiconv.htm,文件名为libiconv-1.9.2-1-lib.zip。

          将libiconv-1.9.2-1-lib.zip解压,将其中的iconv.h放入C:\opt\include目录中,将其中的libiconv.lib放入C:\opt\lib中,并改名为iconv.lib.(没有opt目录就新建一个)。

          解压libxml2-2.7.8.tar.gz文件到C盘根目录,在c:\libxml2-2.7.8\libxml2-2.7.8\win32目录中存放了多个Windows平台编译器的Makefile文件,我们使用vs2008,所以待会会用Makefile.msvc文件。

1.进入Visual Studio 2008 Command Prompt;

2.cd c:\libxml2-2.7.8\libxml2-2.7.8\win32

3.输入cscript configure.js compiler=msvc prefix=c:\opt  include=c:\opt\include lib=c:\opt\lib debug=yes,回车执行。

4.最后使用nmake命令进行编译,输入nmake /f Makefile.msvc并回车。

此时会出现一下错误提示,

Makefile.msvc(465) : fatal error U1020: end-of-file found before next directive
Stop.

网上找了下原因,原来是Makefile.msvc中存在错误。

+!if "$(WITH_ICU)" == "1"
+LIBS = $(LIBS) icu.lib
+!endif

将以上三行前面的+号都删掉,重新执行nmake即可。

在当前win32目录中生成了一个bin.msvc目录,其中就有开发需要的libxml2.lib和libxml2.dll文件。

posted @ 2013-12-25 14:49 brock 阅读(220) | 评论 (0)编辑 收藏