简体   繁体   English

Eclipse - Gradle sourceSets,如何管理我的 yaml 属性文件

[英]Eclipse - Gradle sourceSets, how to manage my yaml property files

I'm using Gradle 7.0 and I made my project using the task Gradle Init.我正在使用 Gradle 7.0,我使用任务 Gradle Init 制作了我的项目。 Then I imported it in Eclipse (2021-03 with buildship 3.1.5).然后我将它导入 Eclipse (2021-03 与 buildship 3.1.5)。 Everything is fine but when I try to read or when I create a file in a java method with "/myfile.yaml" as path, it creates it (or try to read it) in the D:\ root folder (the partition where my eclipse is installed).一切都很好,但是当我尝试读取或在 java 方法中使用“/myfile.yaml”作为路径创建文件时,它会在 D:\ 根文件夹(其中的分区)中创建它(或尝试读取它)我的 eclipse 已安装)。

If I don't use the slash ("myfile.yaml" instead of "/myfile.yaml") the file is created in the root folder of the project.如果我不使用斜杠(“myfile.yaml”而不是“/myfile.yaml”),则在项目的根文件夹中创建文件。 I thought it was supposed to be in src/main/resources until it's not built.我认为它应该在 src/main/resources 中,直到它没有被构建。

My goal is not really to create a file, it was just easier to test.我的目标并不是真正创建一个文件,它只是更容易测试。 My goal is to read some Yaml configuration files.我的目标是阅读一些 Yaml 配置文件。 What should I do to make sure the file will be in the build package and read in the correct place in both context (eclipse debbugging and the build package directory)?我应该怎么做才能确保该文件将在构建 package 中并在两个上下文中读取正确的位置(eclipse 调试和构建 package 目录)? And also, what is the best practice to set the path of the file (sonarlint alerts me about the way I do it: hardcoded in the method below, I know it's not supposed to be like this... I would use a constant but sonarlint doesn't like either).而且,设置文件路径的最佳做法是什么(sonarlint 提醒我我这样做的方式:在下面的方法中硬编码,我知道它不应该是这样的......我会使用一个常量但是sonarlint 也不喜欢)。

The tree of the app:应用程序树:

- Project
    - app
        - src/main/java (containing java classes)
        - src/main/resources (supposing to contain resources, yaml in my case)
        - My build.gradle file
        - yaml file when I try "myfile.yaml" without any /
    - gradle/wrapper/gradle-wrapper.jar & gradle-wrapper.properies
    - gradlew & gradlew.bat
    - settings.gradle

My settings.gradle:我的设置。gradle:

rootProject.name = 'myapp'
include('app')

My build.gradle:我的 build.gradle:

plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    id 'application'
}
apply plugin:'java'
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    implementation 'com.google.guava:guava:30.0-jre'
    // Yaml reader
    implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.12.3'
    testImplementation 'junit:junit:4.13.1'
}

//I tried with and without this sourceSets and the result was the same
sourceSets {
    main {
        java {
            srcDirs= ["src/main/java"]
        }
        resources {
            srcDirs= ["src/main/resources"]
        }
    }
}

application {
    // Define the main class for the application.
    mainClass = 'myapp.launchers.App'
}

And here is the method which writes a file using the Jackson library (yaml):这是使用 Jackson 库(yaml)写入文件的方法:

public static void writeConfiguration() throws JsonGenerationException, JsonMappingException, IOException {
    WorkerConfig wc = new WorkerConfig();
    WorkerPathConfig wpc = new WorkerPathConfig();
    wpc.setTmpdir("\\some\\uri\\file");
    wpc.setOutputdir("\\some\\other\\uri\\file");
    wc.setPathConfig(wpc);
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    objectMapper.writeValue(new File("/application.yaml"), wc);
}

Java Reading Resource Files Java 读取资源文件

You are managing files in your Java program.您正在管理 Java 程序中的文件。 If you are using java.io.File class to get a reference to a specific file it will take those references as actual paths:如果您使用 java.io.File class 来获取对特定文件的引用,它将把这些引用作为实际路径:

  • Absolute path : "/myfile.yaml" -> will point to the root of the hard drive, in your case D:\myfile.yaml绝对路径:“/myfile.yaml”-> 将指向硬盘驱动器的根目录,在您的情况下为 D:\myfile.yaml
  • Relative path : "myfile.yaml" -> will point to the root of your java project相对路径:“myfile.yaml”-> 将指向 java 项目的根目录

Now your goal should be to get the project specific path to load configuration files.现在您的目标应该是获取项目特定的路径来加载配置文件。 This can be achieved with ClassLoader instance.这可以通过 ClassLoader 实例来实现。 You can read the content of the file like in the example below.您可以像下面的示例中那样读取文件的内容。 classLoader.getResourceAsStream() will search for a file inside your resources. classLoader.getResourceAsStream() 将在您的资源中搜索文件。

String fileName = "myfile.yaml";

ClassLoader classLoader = getClass().getClassLoader();

try (InputStream inputStream = classLoader.getResourceAsStream(fileName);
     InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
     BufferedReader reader = new BufferedReader(streamReader)) {

  String line;
  while ((line = reader.readLine()) != null) {
    System.out.println(line);
  }

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

2 Gradle build script 2 Gradle 构建脚本

If you have your classes in "src/main/java" and resource files in "src/main/resources" then this is compliant with the convention of gradle java plugin and you don't need to specify explicitly sourceSets block in your Gradle build script.如果您在“src/main/java”中有您的类,在“src/main/resources”中有资源文件,那么这符合gradle java 插件的约定,并且您不需要在 Z3DCABB201716ECE176 中明确指定sourceSets块脚本。

  1. Sonar warning声纳警告

You can extract file name as a constant and pass it as a parameter when loading the configuration file.您可以将文件名提取为常量,并在加载配置文件时将其作为参数传递。 I suppose this file "myfile.yaml" is convention of your application.我想这个文件“myfile.yaml”是你的应用程序的约定。 In a best case it's documented somewhere.在最好的情况下,它记录在某处。

At least this will greatly ease up development, instead if you would want to have it provided dynamically you would need to read file name from environmental variable or an argument provided in main method.至少这将大大简化开发,相反,如果您希望动态提供它,则需要从环境变量或 main 方法中提供的参数中读取文件名。

You can suppress SonarQube warning if it doesn't apply in your case and explain why you ignored it.如果 SonarQube 警告不适用于您的情况,您可以取消它,并解释您忽略它的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM