我在Intellij Idea和Windows 8.1上閱讀文件遇到了一些奇怪的麻煩。無法讀取Intellij上沒有額外前綴的文件
而且我總是得到FileNotFoundException
。
下面是代碼片段:
public XlsReader(String fileName, String sheetName) {
open(fileName, sheetName);
}
public void open(String fileName, String sheetName) {
InputStream fis = null;
try {
if (sheetName == null || sheetName.isEmpty()) {
throw new IllegalArgumentException("Please, provide sheet name");
}
Logger.logDebug("PATH: " + new File(".").getAbsolutePath());
fis = new FileInputStream(fileName);
String resourceFilePath = this.getClass().getResource(fileName).getFile();
Logger.logDebug(resourceFilePath);
fis = new FileInputStream(resourceFilePath);
XSSFWorkbook workBook = new XSSFWorkbook(fis);
sheet = workBook.getSheet(sheetName);
getMetaData();
我不明白爲什麼在這條線:
new FileInputStream(fileName)
我有此異常。 並且當從以下位置開始切換路徑時:
xls = new XlsReader(「InputDataIndirect.xlsx」,「Calculator」);
到:
XLS =新XlsReader( 「測試/ InputDataIndirect.xlsx」, 「計算器」);
它現在有效。
這裏是項目struckture:
我試圖加載從類路徑文件以及this.getClass().getResource(fileName).getFile()
但沒有成功。
有什麼建議嗎?
你能告訴我們你的目錄結構是什麼樣的嗎?源代碼在哪裏,InputDataIndirect.xlsx在哪裏? – Trisha
@Trisha我添加了項目視圖。 –
如果您正在IntelliJ構思中運行主要方法或測試,它將使用項目的根目錄作爲根目錄來加載文件。因此,它將顯示在new_automation下,因此您需要將「test」文件夾添加到路徑中。要改變這一點,你可以在你的運行配置中改變工作目錄的位置。或者,這篇文章的一些評論和答案可能會有所幫助http://stackoverflow.com/questions/32094701/access-resource-folder-within-jar – Trisha