在windows環境運行,下面的springboot中path怎么找不到文件呢? path輸出后的結果是:路徑是多少:/D:/bjpowernode/msb/%e4%b9%90%e4%b9%8b%e8%80%85/apache%20commons/SpringBootBase6/target/test-classes/1.txt 怎么解決一下呢? import cn.hutool.core.io.FileUtil; public class FileUtilTest { @Test public void test3() { String path = FileUtilTest.class.getResource("/1.txt").getPath(); System.out.println("路徑是多少:"+path); } }
在Windows環境下,當你使用Class.getResource()方法獲取資源路徑時,可能會遇到路徑格式問題,特別是涉及到URL編碼(如空格被轉換為%20,中文字符被轉義等)的情況。從你提供的路徑輸出結果來看,確實存在這種URL編碼的問題。
解決方案
要解決這個問題,你可以采取以下幾種方法之一:
方法一:使用Paths.get(URL.toURI())來正確處理路徑
Java的Paths類和URI類可以幫助我們正確處理這些轉義字符,并生成正確的文件系統路徑。以下是修改后的代碼示例:
Java
深色版本
import cn.hutool.core.io.FileUtil;
import org.junit.Test;
import java.net.URL;
import java.nio.file.Paths;
public class FileUtilTest {
? ? @Test
? ? public void test3() throws Exception {
? ? ? ? URL resourceUrl = FileUtilTest.class.getResource("/1.txt");
? ? ? ? String path = Paths.get(resourceUrl.toURI()).toString();
? ? ? ? System.out.println("路徑是多少:" + path);
? ? ? ? // 如果你需要讀取文件內容,可以繼續使用path變量
? ? ? ? byte[] bytes = FileUtil.readBytes(path);
? ? ? ? System.out.println("bytes.length=" + bytes.length);
? ? }
}
方法二:直接使用getResourceAsStream()
為了避免路徑轉換帶來的問題,可以直接使用getResourceAsStream()方法來獲取輸入流,而不是嘗試將URL轉換為文件路徑。這種方法更加通用且不易出錯:
Java
深色版本
import cn.hutool.core.io.IoUtil;
import org.junit.Test;
import java.io.InputStream;
public class FileUtilTest {
? ? @Test
? ? public void test3() throws Exception {
? ? ? ? InputStream inputStream = FileUtilTest.class.getResourceAsStream("/1.txt");
? ? ? ? if (inputStream == null) {
? ? ? ? ? ? System.out.println("資源未找到!");
? ? ? ? ? ? return;
? ? ? ? }
? ? ? ? byte[] bytes = IoUtil.readBytes(inputStream);
? ? ? ? System.out.println("bytes.length=" + bytes.length);
? ? ? ? // 確保關閉輸入流
? ? ? ? IoUtil.close(inputStream);
? ? }
}
總結
方法一適用于你需要獲得實際的文件系統路徑的情況。
方法二更為推薦,尤其是在處理資源文件時,因為它避免了與操作系統相關的路徑問題,并且能夠很好地處理打包到JAR中的情況。
根據你的具體情況選擇合適的方法進行調整即可解決問題。如果1.txt文件是作為測試資源的一部分,請確保它位于src/test/resources/目錄下,并且已經被正確地包含在構建路徑中。