前面文章介绍了使用Servlet读取文件的方法【ServletConfig对象和ServletContext对象的应用_এ揽风挽你ꦿ໊ོ༊130的博客-CSDN博客】
这章介绍一下使用普通java类获取外部资源文件的两种方法
一、首先创建一个properpties文件,在里面一键值对的形式输入内容
二、然后创建一个普通java类用来读取 properpties文件里的内容
1.方式一:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 使用普通java类读取外部资源文件
*
*/
public class ReadFileDome {
public void readFile(String Path){
//方式一:
InputStream in = ReadFileDome.class.getClassLoader().getResourceAsStream(Path);
Properties p = new Properties();
try {
p.load(in);
String url = (String) p.get("url");//这里的url为我们要读取的文件里的一个内容
System.out.println(url);
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.方式二:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 使用普通java类读取外部资源文件
*
*/
public class ReadFileDome {
public void readFile(String Path){
//方式二:
String pathlath = ReadFileDome.class.getClassLoader().getResource(Path).getPath();
try {
InputStream i = new FileInputStream(pathlath);
Properties p = new Properties();
try {
p.load(i);
System.out.print(p.getProperty("url"));//这里的url为我们要读取的文件里的一个内容
}catch (IOException e){
e.printStackTrace();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
三、接着创建一个Servlet来执行上面普通java方法类
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/ServletDome")
public class ServletDome extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
new ReadFileDome().readFile("File/pro.properties");//这里跟文件的相对路劲
}
}
最后附上运行结果截图