Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法获取放置在类旁边的文件的URL_Java_File_File Io_Classpath - Fatal编程技术网

Java 无法获取放置在类旁边的文件的URL

Java 无法获取放置在类旁边的文件的URL,java,file,file-io,classpath,Java,File,File Io,Classpath,我试图获取放在java类旁边的文本文件的URL(以允许快速创建测试数据),但我遇到了一个问题,即无法获取放在java类旁边的文件的URL,该文件应该位于jar中 代码测试文件读取器: package test.util.files; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import com.google.common.base.Verify; im

我试图获取放在java类旁边的文本文件的URL(以允许快速创建测试数据),但我遇到了一个问题,即无法获取放在java类旁边的文件的URL,该文件应该位于jar中

代码测试文件读取器:

package test.util.files;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import com.google.common.base.Verify;
import com.google.common.io.Resources;

public class TestFileReader {
    /**
     * Reads test file contents to string.
     * Test file is expected to be right next to the given class.
     */
    public static <T> String readTestFileToString(
        final Class<T> clazz,
        final String fileName) {

        final URL url = clazz.getClassLoader().getResource(fileName);
        Verify.verify(url != null);

        try {
            return Resources.toString(url, StandardCharsets.UTF_8);
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
    }
}

hi.txt
文件位于同一java包中的
TestFileReaderTest.java
文件旁边

验证时代码失败。验证(url!=null)


如何获取放在java类旁边的文本文件的URL?

您可以尝试将
hi.txt
放在jar的根路径中,而不是放在
TestFileReaderTest.java
旁边。
package tst_of_test_utils.test.util.files;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;

import test.util.files.TestFileReader;

class TestFileReaderTest {
    @Test
    void WHEN_valid_file_SHOULD_read_in_test_file() throws Exception {

        final String content = TestFileReader.readTestFileToString(TestFileReaderTest.class, "hi.txt");

        Assertions.assertThat(content).isEqualTo("content-val");
    }
}