Загрузка файлов в Java в разработке плагинов Intellij idea - PullRequest
0 голосов
/ 29 июня 2018

Я делаю плагин генератора Spring Boot и хочу загрузить некоторые файлы шаблонов с Velocity и / или Java. Предпочтительная Java.

Теперь проблема в том, что я просто не могу понять, как прочитать файл шаблона * .vm на Java и преобразовать его в строковую переменную.

Итак, здесь, на моем скриншоте, я хочу загрузить свой «java_dto.vm», например, в Java, чтобы его содержимое было преобразовано в строку.

Структура папок и файлов плагина, который я разрабатываю

Вот так выглядит мой файл Java_dto.vm:

package $dtoPackage;
public class $entityName#[[Dto]]# {
    public $entityName#[[Dto]]#() {

  }
}

Я попробовал некоторые вещи в обычном классе Java, чтобы загрузить файл, который был успешным. Но в самом плагине сейчас я не могу заставить это работать.

Итак, это НЕ мой плагин, а пример, в котором я его опробовал.

Структура проекта кода пробной загрузки для загрузки в файл

С кодом я все испробовал и все заработало.

`
package com.tutorialspoint;

import org.apache.commons.text.StringSubstitutor;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {

  public static void main(String[] args) {


    try {
        // Determine where the input file is; assuming it's in the same 
           directory as the jar
        String fileName = "java_dto.vm";
        File jarFile = new File(Main.class.getProtectionDomain()
        .getCodeSource().getLocation()
        .toURI().getPath());           
        String inputFilePath = jarFile + File.separator + 
        "com\\tutorialspoint\\templates\\" + fileName;

        Path path = Paths.get(inputFilePath);
        String stringFromFile = 
        java.nio.file.Files.lines(path).collect(Collectors.joining());

        Path path2 = Paths.get(inputFilePath);

        String stringFromFile2 = new 
        String(java.nio.file.Files.readAllBytes(path2));

        FileInputStream inStream = new FileInputStream(new 
        File(inputFilePath));

        try {

            // Read in the contents of the input file in a single gulp
            FileChannel fc = inStream.getChannel();
            MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, 
            fc.size());

          System.out.println(Charset.defaultCharset().decode(bb).toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            inStream.close();
        }

    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
    }


    //---------

    try {
        // Determine where the input file is; assuming it's in the same 
        directory as the jar
        String fileName = "java_dto.vm";
        File jarFile = new 
        File(Main.class.getProtectionDomain().getCodeSource()
        .getLocation().toURI().getPath());
        String inputFilePath = jarFile + File.separator +
        "com\\tutorialspoint\\templates\\" + fileName;

        FileInputStream inStream = new FileInputStream(
        new File(inputFilePath));

        try {

            // Read in the contents of the input file in a single gulp
            FileChannel fc = inStream.getChannel();
            MappedByteBuffer bb = fc.map(
             FileChannel.MapMode.READ_ONLY, 0, fc.size());

          System.out.println(Charset.defaultCharset().decode(bb).toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            inStream.close();
        }

    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
    }

    //---------

    try {
        // Determine where the input file is; assuming it's in the same directory as the jar
        String fileName = "java_dto.vm";
        File jarFile = new File(Main.class.getProtectionDomain()
        .getCodeSource().getLocation().toURI().getPath());
        String inputFilePath = jarFile.getParent() + File.separator + 
        "untitled1\\com\\tutorialspoint\\" + fileName;
        FileInputStream inStream = new FileInputStream(
                                new File(inputFilePath));

        try {

            // Read in the contents of the input file in a single gulp
            FileChannel fc = inStream.getChannel();
            MappedByteBuffer bb = fc.map(
            FileChannel.MapMode.READ_ONLY, 0, fc.size());

            // Do something with the read in data
            System.out.println("-----------");
            // hier wordt content uitgeprint

        System.out.println(Charset.defaultCharset().decode(bb).toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            inStream.close();
        }

    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
    }


    Map<String, String> valuesMap = new HashMap<String, String>();
    valuesMap.put("animal", "quick brown fox");
    valuesMap.put("target", "lazy dog");
    String templateString = "The ${animal} jumped over the ${target}.";

    System.out.println("templateString is: ");
    System.out.println(templateString);

    StringSubstitutor sub = new StringSubstitutor(valuesMap);
    String resolvedString = sub.replace(templateString);

    String s = new StringBuilder()
            .append("line1\n")
            .append("line2\n")
            .append("line3\n")
            .toString();
    System.out.println(s);

    String ss = new StringBuilder()
            .append("package $dtoPackage;")
            .append("\n")
            .append("\n")
            .append("public class $entityName#[[Dto]]# {")
            .append("\n")
            .append("\n")
            .append("public void haha() { ")
            .append("\n")
            .append("\n")
            .append("}")
            .append("\n")
            .append("}").toString();
    System.out.println(ss);

    String java_test = "package ${dtoPackage};" +
            "\n" +
            "\n" +
            "public class ${entityName}#[[Dto]]# {" +
            "\n" +
            "\n" +
            " public void haha() { " +
            "\n" +
            " } " +
            " \n " +
            "}";

    Map<String, String> valuesTest = new HashMap<String, String>();
    valuesTest.put("dtoPackage", "com.filip.springboot.dto");
    valuesTest.put("entityName", "Test");

    StringSubstitutor subtest = new StringSubstitutor(valuesTest);
    String resolvedStringTest = subtest.replace(java_test);

    }
 }

`

Кто-нибудь знает, что это можно исправить / решить, чтобы использовать в плагине для intellij идея? Таким образом, нет диалогового окна filechooser, имя уже известно и местоположение (в папке шаблонов).

Спасибо уже за ваше внимание.

Если что-то не понятно, дайте мне знать, пожалуйста.

Filip

...