package com.zzsn.config;

import com.hankcs.hanlp.corpus.io.IIOAdapter;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Properties;

@Component
public class ResourceIOAdapter implements IIOAdapter {
    @Override
    public InputStream open(String path) throws IOException {
        Properties properties = System.getProperties();
        String s = properties.getProperty("user.dir");
        if (properties.getProperty("os.name").toLowerCase().contains("win")) {
            s += "\\";
        }else {
            s += "/";
        }
//        将符号“\\”和“\”替换成“/”,有时候便于统一的处理路径的分隔符,避免同一个路径出现两个或三种不同的分隔符
        path = (s+path).replace("\\", "/").replace("\\\\", "/");
        ClassPathResource resource = new ClassPathResource(path);
        InputStream is = new FileInputStream(resource.getFile());
        return is;
    }

    @Override
    public OutputStream create(String path) throws IOException {
        Properties properties = System.getProperties();
        String s = properties.getProperty("user.dir");
        if (properties.getProperty("os.name").toLowerCase().contains("win")) {
            s += "\\";
        }else {
            s += "/";
        }
//        将符号“\\”和“\”替换成“/”,有时候便于统一的处理路径的分隔符,避免同一个路径出现两个或三种不同的分隔符
        path = (s+path).replace("\\", "/").replace("\\\\", "/");
        ClassPathResource resource = new ClassPathResource(path);
        OutputStream os = new FileOutputStream(resource.getFile());
        return os;
    }
}