String file= new File(ResourceUtils.getURL("classpath:json/LalJson").getPath()).getAbsolutePath();
String file= new ClassPathResource("json/LalJson").getFile().getPath();
上述方式測試可用,部署jar包不可用
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("json/LalJson");
String file= readFile(inputStream)
上述方法部署jar包可用
其readFile方法如下
/*
* 讀取檔案内容
*/
public static String readFile ( 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 filter( builder.toString());
}
filter方法如下
// 過濾輸入字元串, 剔除多行注釋以及替換掉反斜杠
public static String filter ( String input ) {
return input.replaceAll( "/\\*[\\s\\S]*?\\*/", "" );
}