0

私は Gradle 7.0 を使用しており、タスク Gradle Init を使用してプロジェクトを作成しました。次に、それを Eclipse (2021-03 with buildship 3.1.5) にインポートしました。すべて問題ありませんが、パスとして「/myfile.yaml」を使用してJavaメソッドでファイルを読み取ろうとするか作成すると、D:\ルートフォルダー(パーティション私の日食がインストールされています)。

スラッシュ (「/myfile.yaml」ではなく「myfile.yaml」) を使用しない場合、ファイルはプロジェクトのルート フォルダーに作成されます。ビルドされるまでは src/main/resources にあるはずだと思っていました。

私の目標は実際にはファイルを作成することではなく、テストが簡単だっただけです。私の目標は、いくつかの Yaml 構成ファイルを読み取ることです。ファイルがビルド パッケージにあり、両方のコンテキスト (Eclipse デバッグとビルド パッケージ ディレクトリ) で正しい場所に読み込まれるようにするにはどうすればよいですか? また、ファイルのパスを設定するためのベストプラクティスは何ですか (sonarlint は、私がそれを行う方法について警告します: 以下の方法でハードコーディングされています。 sonarlint も好きではありません)。

アプリのツリー:

- 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

私のsettings.gradle:

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

私の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'
}

そして、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);
}
4

1 に答える 1