After Springboot is packaged, it reads the files under the classpath

A configuration file is added under the springboot project resource, which can be read normally in the local test through the following subsections

ResourceUtils.getFile("classpath:/ca/enterprise.xx");

 In the docker container deployed as a jar deployed to the test environment, an error was reported that the files in the jar package could not be read. Attempts of various reading methods, and finally the following methods can be used to read normally

 

	/**
	 * Read the object in the jar package
	 * @param enterpriseCerFilePath
	 * @return
	 * @throws IOException
	 */
	public String getSignCertByJarFile(String enterpriseCerFilePath) throws IOException
	{
		FileInputStream fileInputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader bufferedReader = null;
		try{
			InputStream stream = getClass().getClassLoader().getResourceAsStream(enterpriseCerFilePath);
			inputStreamReader = new InputStreamReader(stream); // Create an input stream object reader
			bufferedReader = new BufferedReader(inputStreamReader); // Create an object that converts the content of the file into a language that the computer can understand
			StringBuffer stringBuffer = new StringBuffer();
			String line= bufferedReader.readLine().trim();
			while (line != null) {
				stringBuffer.append(line);
				line = bufferedReader.readLine(); // read in one line at a time
			}
			return stringBuffer.toString();
		} catch (IOException ioe) {
			yes.printStackTrace ();
			throw ioe;
		}finally{
			if(null != bufferedReader) bufferedReader.close();
			if(null != inputStreamReader) inputStreamReader.close();
			if(null != fileInputStream) fileInputStream.close();
		}
	}


	public String getSignCertByJarFile2(String enterpriseCerFilePath) throws IOException
	{
		FileInputStream fileInputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader bufferedReader = null;
		try{

			ClassPathResource ClassPathResource = new ClassPathResource(enterpriseCerFilePath);
			bufferedReader = new BufferedReader(new InputStreamReader(ClassPathResource.getInputStream()));

			StringBuffer stringBuffer = new StringBuffer();
			String line= bufferedReader.readLine().trim();
			while (line != null) {
				stringBuffer.append(line);
				line = bufferedReader.readLine(); // read in one line at a time
			}
			return stringBuffer.toString();
		} catch (IOException ioe) {
			yes.printStackTrace ();
			throw ioe;
		}finally{
			if(null != bufferedReader) bufferedReader.close();
			if(null != inputStreamReader) inputStreamReader.close();
			if(null != fileInputStream) fileInputStream.close();
		}
	}

 

Record the solution first, and then write the specific reasons. The file reading in the jar package is not the same as the file reading in the application.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326076714&siteId=291194637