作者:fstimer 出處:https://www.cnblogs.com/fstimers/ 歡迎轉載,也請保留這段聲明。謝謝!
簡介
最近有個需求,需要發送一個上傳文件的請求,為了盡可能模擬用戶操作,所以要傳入文件路徑,而不直接是文件的內容(需要文件的路徑,不是獲取文件內容),使用this.getClass().getClassLoader().getResource("文件名").getPath()獲取項目中文件路徑(其它集中獲取文件路徑的方法請參考獲取文件路徑),未打成jar前一切正常運行,打成jar包后程序就會提示路徑異常。
原因:當打成一個jar包后,整個jar包是一個文件,只能使用流的方式讀取資源,這時候就不能通過File來操作資源了。在IDE中之所以能正常運行,是因為IDE中的資源文件在target/classes目錄下,是正常的文件系統結構。
解決方案
最后實在沒有辦法,只能創建臨時文件,用流讀取文件內容輸出到臨時文件中,來獲取臨時文件路徑代替項目中文件路徑。具體實現如下:
import org.testng.annotations.Test;
import java.io.*;
public class JarPathTest {
@Test
public void getPathTest() {
String fileName = "filePath.xlsx";
String filepath = getUploadResource(fileName);
System.out.println(filepath);
}
public String getUploadResource(String fileName) {
//返回讀取指定資源的輸入流
InputStream is = this.getClass().getResourceAsStream("/files/" + fileName);
//若文件已存在,則返回的filePath中含有"EXIST",則不需再重寫文件
String filePath = createFile(fileName);
//文件不存在,則創建流輸入默認數據到新文件
if (!filePath.contains("EXIST")) {
File file = new File(filePath);
inputStreamToFile(is, file);
return filePath;
}
return filePath.substring(5);
}
public String createFile(String filename) {
String path = System.getProperty("user.dir");
//create folder
String dirPath = path + File.separator + "uploadFiles";
File dir = new File(dirPath);
dir.mkdirs();
//create file
String filePath = dirPath + File.separator + filename;
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
return "EXIST" + filePath;
}
public void inputStreamToFile(InputStream ins, File file) {
OutputStream os = null;
try {
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = ins.read(buffer, 0, 1024)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
有的返回值中之所以加了“EXIST”,是為了避免已存在的同名文件被重寫。
附錄:
InputStream,String,File相互轉化方式 :https://www.cnblogs.com/cpcpc/archive/2011/07/08/2122996.html
