我是参考这个文档写的:
Sprint Boot 工程中HanLP配置路径BUG解决 | 贫贫贫贫僧 (haoyuanliu.github.io)
问题
问题一:
在Spring Boot工程中使用HanLP工具,按照平常的配置,将根路径配置为root=src/main/resources/HanLP/
始终加载不成功,总是显示Caused by: java.lang.IllegalArgumentException: 核心词典src/main/resources/HanLP/data/dictionary/CoreNatureDictionary.txt加载失败
问题二:
当时还参考其他的资料,试着把配置文件hanlp.properties,提到和src一个目录等级,这样虽然不报错,但是并没有访问到我在resource下的自定义词典
解决
我当时使用这个相对路径一直不行,但是使用绝对路径又可以,后来才发现应该是hanlp对于相对路径设置有点问题
然后根据搜索到的大佬讲解,添加一个下面这种适配器就可以了
补充
root=HanLP/
IOAdapter=com.shang.elasticsearch.config.ResourceFileIoAdapter
package com.baishang.elasticsearch.config;
import com.hankcs.hanlp.corpus.io.IIOAdapter;
import org.springframework.core.io.ClassPathResource;
import java.io.*;
import java.nio.file.Files;
public class ResourceFileIoAdapter implements IIOAdapter {
@Override
public InputStream open(String path) throws IOException {
ClassPathResource resource = new ClassPathResource(path);
// return Files.newInputStream(resource.getFile().toPath());
// Linux环境下跑要把open()里改成这样:
return resource.getInputStream();
}
@Override
public OutputStream create(String path) throws IOException {
ClassPathResource resource = new ClassPathResource(path);
return Files.newOutputStream(resource.getFile().toPath());
}
}