| @@ -4,6 +4,15 @@ import com.cybozu.labs.langdetect.Detector; | |||
| import com.cybozu.labs.langdetect.DetectorFactory; | |||
| import com.cybozu.labs.langdetect.LangDetectException; | |||
| import lombok.extern.slf4j.Slf4j; | |||
| import lombok.var; | |||
| import org.springframework.core.io.Resource; | |||
| import org.springframework.core.io.support.PathMatchingResourcePatternResolver; | |||
| import sun.misc.IOUtils; | |||
| import java.io.IOException; | |||
| import java.io.InputStream; | |||
| import java.util.ArrayList; | |||
| import java.util.List; | |||
| @Slf4j | |||
| public class LanguageDetect { | |||
| @@ -13,8 +22,28 @@ public class LanguageDetect { | |||
| private static void initDetector(){ | |||
| if(detect == null){ | |||
| try { | |||
| DetectorFactory.loadProfile(LanguageDetect.class.getClassLoader().getResource("profiles").getPath()); | |||
| detect = DetectorFactory.create(); | |||
| List<String> profile = new ArrayList<>(); | |||
| try { | |||
| PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); | |||
| Resource[] resources = resolver.getResources("classpath:profiles/*"); | |||
| for (Resource resource:resources) { | |||
| try { | |||
| byte[] bytes = new byte[0]; | |||
| bytes = new byte[resource.getInputStream().available()]; | |||
| resource.getInputStream().read(bytes); | |||
| profile.add(new String(bytes)); | |||
| } catch (IOException e) { | |||
| e.printStackTrace(); | |||
| } | |||
| } | |||
| } catch (IOException e) { | |||
| e.printStackTrace(); | |||
| } | |||
| if(!profile.isEmpty()){ | |||
| DetectorFactory.loadProfile(profile); | |||
| detect = DetectorFactory.create(); | |||
| } | |||
| } catch (LangDetectException e) { | |||
| e.printStackTrace(); | |||
| log.error("语言检测初始化错误。"+e.getMessage()); | |||
| @@ -45,7 +74,29 @@ public class LanguageDetect { | |||
| return null; | |||
| } | |||
| public static void main(String[] args) { | |||
| System.out.println(detect("aa")); | |||
| var resolver = new PathMatchingResourcePatternResolver(); | |||
| Resource[] resources = new Resource[0]; | |||
| try { | |||
| resources = resolver.getResources("classpath:profiles/*"); | |||
| } catch (IOException e) { | |||
| e.printStackTrace(); | |||
| } | |||
| for (var resource:resources) { | |||
| System.out.println(resource.getFilename()); | |||
| try { | |||
| byte[] bytes = new byte[0]; | |||
| bytes = new byte[resource.getInputStream().available()]; | |||
| resource.getInputStream().read(bytes); | |||
| String str = new String(bytes); | |||
| System.out.println(str); | |||
| } catch (IOException e) { | |||
| e.printStackTrace(); | |||
| } | |||
| } | |||
| // System.out.println(detect("aa")); | |||
| } | |||
| } | |||