springboot打成jar包後讀取配置resources下的文件

之前是這樣讀取的  打成jar放到linux  報路徑問題 ,jar包找不到classpath的路徑

String rootPath = this.getClass().getResource("config.json").getPath();
response.getWriter().write(readFile(inputStream));

	public String readFile(String path) throws IOException {
		StringBuilder builder = new StringBuilder();
		try {
			path = ImgCtl.class.getClassLoader().getResource(path).getPath();
			InputStreamReader reader = new InputStreamReader(new FileInputStream(path), "UTF-8");
			BufferedReader bfReader = new BufferedReader(reader);
			String tmpContent = null;
			while ((tmpContent = bfReader.readLine()) != null) {
				builder.append(tmpContent);
			}
			bfReader.close();
		} catch (UnsupportedEncodingException e) {
			// 忽略
		}
		return this.filter(builder.toString());
	}
/**
	 * 過濾輸入字符串, 剔除多行註釋以及替換掉反斜槓
	 */
	public String filter(String input) {
		return input.replaceAll("/\\*[\\s\\S]*?\\*/", "");
	}

解決方法 用這種方式

InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.json");

		//String rootPath = this.getClass().getResource("/public/ueditor/jsp/config.json").getPath();
		//System.out.println(rootPath);

		//ClassPathResource resource = new ClassPathResource("public/ueditor/jsp/config.json");
		response.getWriter().write(readFileN(inputStream));
/*
	 * 讀取配置文件
	 */
	private String readFileN ( InputStream inputStream ) throws IOException {

		StringBuilder builder = new StringBuilder();
		try {
			InputStreamReader reader = new InputStreamReader(inputStream , "UTF-8" );
			BufferedReader bfReader = new BufferedReader( reader );
			String tmpContent = null;
			while ( ( tmpContent = bfReader.readLine() ) != null ) {
				builder.append( tmpContent );
			}
			bfReader.close();
		} catch ( UnsupportedEncodingException e ) {
			// 忽略
		}
		return this.filter( builder.toString() );
	}

參考博客:https://blog.csdn.net/cscscssjsp/article/details/84822706

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章