簡體   English   中英

從類路徑加載文件

[英]loading a file from classpath

我有一行代碼:java File file = new File(getFile()) HandleData.java

方法 - getFile()獲取屬性fileName的值。 fileName通過application_context.xml注入,類的bean部分--HandleData如下:

 <bean id="dataHandler" class="com.profile.transaction.HandleData">
 <property name="fileName" value="DataFile.xml"></property>
 </bean>

我成功構建了項目並檢查了DataFile.xml WEB-INF/classes存在DataFile.xml HandleData.class存在於WEB-INF/classes/com/profile/transacon

但是當我運行它時會拋出filenotfound異常。 如果我注入絕對路徑( C:\\MyProjectWorkspace\\DataProject\\target\\ProfileService\\WEB-INF\\classes\\DataFile.xml它會成功找到該文件。)。

有人可以幫助確定要注入的正確路徑,以便從類路徑中獲取文件嗎?

雖然注入File通常是首選方法,但您也可以利用Spring的ResourceLoader動態加載資源。

通常,這就像將ResourceLoader注入Spring bean一樣簡單:

@Autowired
private ResourceLoader resourceLoader;

然后從類路徑加載:

resourceLoader.getResource("classpath:myfile.txt");

你應該有:

<property name="fileName" value="classpath:DataFile.xml" />

它應該作為org.springframework.core.io.Resource注入,類似於這個答案

由於OP只是通過spring注入fileName,還是想通過代碼創建File對象,你應該使用ClassLoadeer來讀取文件

嘗試這個

InputStream is =  HandleData.class.getClassLoader().getResourceAsStream(getFile()));

編輯

下面是代碼的剩余部分,用於讀取文件

BufferedInputStream bf = new BufferedInputStream(is);
DataInputStream dis = new DataInputStream(bf);

while (dis.available() != 0) {
    System.out.println(dis.readLine());
}

編輯2

因為你想要它作為文件對象,要獲取FileInputStream

嘗試這個

 FileInputStream fisTargetFile = new FileInputStream(new File(HandleData.class.getClassLoader().getResource(getFile()).getFile()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM