获取类路径下的资源

package cn.ttt.servlet;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 演示获取类路径下的资源
 */
@WebServlet("/AServlet")
public class AServlet extends HttpServlet {

    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		/*
		 * 1.得到ClassLoader
		 * 	>先得到Class,再得到ClassLoader
		 * 2.调用getResourceAsStream(),得到一个InputStream
		 */
		ClassLoader c1 = this.getClass().getClassLoader();
		InputStream input = c1.getResourceAsStream("a.txt");
		
		/*String s = IOUtils.toString(input);
		System.out.println(s);*/
	}

	

}

你可能感兴趣的:(获取类路径下的资源)