1. 程式人生 > >maven有關resource資源的管理和訪問

maven有關resource資源的管理和訪問

這裡所說的resource主要說的是pom裡面build下的設定項。

可以參考maven官網文件:http://maven.apache.org/pom.html#Resources,有好心人把它給翻譯了一遍偷笑http://blog.csdn.net/tomato__/article/details/13625497 

我這裡主要的設定如下:

<build>
  	<!-- 預設goal -->
  	<defaultGoal>package</defaultGoal>

  	<!-- 輸出目標目錄 -->
  	<directory>Debug</directory>

  	<!--  buid出來的檔案命名,不設定的情況下,會根據artifactid和version自動生成-->
  	<finalName>測試工具${project.artifactId}-${project.version}</finalName>

	<!-- 程式碼路徑,原生maven工程其實不需要單獨設定,java工程轉換而來的最好設定一下 -->
    <sourceDirectory>src</sourceDirectory>

    <resources>
	    <resource>

	    	<!-- 資源路徑,原生maven工程其實不需要單獨設定,java工程轉換而來的需要設定,否則找不到,
	    		因為maven是典型的約定程式設計,遵循約定優於配置 -->
	        <directory>${basedir}/resources</directory>

			<!-- 資源打包後在jar中的路徑,這裡比較坑爹,之前沒設定,結果生成到了jar的根路徑下,
				而在訪問的時候仍然使用的是directory的路徑 -->
	        <targetPath>resources</targetPath>
	    </resource>
    </resources>
……
</build>
我們把工程打成jar包之後,如果要把resource中的資源再釋放出來,程式碼如下
/**
	 *	把jar中指定路徑的資源轉換為inputstream
	 * @param in rerouces資源的相對路徑
	 * @return
	 * @throws IOException
	 */
	public String resSaveToDisk(String in) throws IOException {
		boolean result = true;
		String filePath = (System.getProperty("user.dir") + "/" + in).replace(
				"\\", "/");
		// System.out.println(filePath);
		try {
			File file = new File(filePath);
			File dir;
			if (!(dir = new File(file.getAbsolutePath())).exists()) {
				dir.mkdirs();
			}
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
			inputstreamtofile(this
					.getClass().getClassLoader().getResourceAsStream(in), file);


		} catch (Exception ex) {
			result = false;
		}
		return filePath;
	}



	/**
	 *inputsream的資料寫入檔案
	 * @param ins
	 * @param file
	 * @throws IOException
	 */
	// 檔案寫入
	public void inputstreamtofile(InputStream ins, File file)
			throws IOException {

		int readLenth =8000;
		OutputStream os = new FileOutputStream(file);

		int bytesRead = 0;
		byte[] buffer = new byte[readLenth];

		while ((bytesRead = ins.read(buffer, 0, readLenth)) >0) {
			// DebugLogger.getInstance().log("read a section");
			os.write(buffer, 0, bytesRead);
			os.flush();
		}
		os.close();
		ins.close();
	}