Java 无法获取放置在类旁边的文件的URL
我试图获取放在java类旁边的文本文件的URL(以允许快速创建测试数据),但我遇到了一个问题,即无法获取放在java类旁边的文件的URL,该文件应该位于jar中 代码测试文件读取器: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
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");
}
}