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();
	}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值