Java读取.properties配置文件的几种方法
在做java工程时,经常会将一些配置信息放到.properties文件中,需要用时再去对应的文件中读取,下面提供几种常用的读取.properties文件的方法,并列举这些方法的特点。
一、读文件方式读取.properties文件。
关键代码如下:
try{
// 创建Properties对象
Properties p = new Properties();
// 设置读取文件路径
String s_xmlpath="config.properties";
InputStream io=Test.class.getClassLoader().getResourceAsStream(s_xmlpath);
// 加载文件
p.load(io);
// 取得文件的值
system.out.println(p.getProperty("key"));
// 关闭流
io.close();
}catch(Exception ex){
ex.printStackTrace();
}
该方法可放到Servlet中,在工程初期化时一次性加载配置文件,具体代码如下:
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test extends HttpServlet {
public static Properties p;
private static Test instance = null;
/**
* Constructor of the object.
* 默认构造方法
*/
public Test() {
super();
}
/**
* Constructor of the object.
* 私有构造方法,调用init()方法读取配置文件
*/
private Test(String str) {
super();
try {
this.init();
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 静态方法,取得对象实例
* @return
*/
public static Test getInstance()
{
// 当前实例为空时
if(instance == null)
{
instance = new Test("");
}
return instance;
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log // Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
……
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
……
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
try{
// 创建Properties对象
p = new Properties();
// 设置读取文件路径
String s_xmlpath="sql.properties";
InputStream io=Test.class.getClassLoader().getResourceAsStream(s_xmlpath);
// 加载文件
p.load(io);
// 关闭流
io.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
在工程的web.xml文件中添加以下配置:
经过以上配置,可以通过Test类的静态属性读取配置文件中的值。
String str = Test.p.getProperty(“key”);
二、资源文件绑定的方式读取配置文件
关键代码:
// 定义资源绑定变量
ResourceBundle bundle = ResourceBundle.getBundle("config");
String value = bundle.getString(“key”);
可将该段代码写在静态块中,在需要读取文件的时候调用。
示例代码:
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* 读取配置文件config.properties
* @author Lee
*
*/
public class ReadConfigProperties {
// 定义资源绑定变量
private static final ResourceBundle bundle;
static {
// 读取propertiest资源文件
bundle = ResourceBundle.getBundle("config");
}
/**
* 根据name获得字符串的名
*
* @param name
* @return String
*/
public static String getString(String name) {
String value = null;
try {
value = bundle.getString(name);
value = new String(value.getBytes("ISO8859-1"), "UTF-8");
} catch (MissingResourceException e) {
System.err.println(e);
} catch (Exception ee) {
System.err.println(ee);
}
if ("".equals(value)) {
return null;
} else {
return value;
}
}
}
项目中,经常把一部分功能独立出来,做一个java project,然后打成jar包供其他项目引用。这时候,如果jar包中需要读取配置文件信息,则很少把该配置打进jar包,因为它不方便修改,更多都是采用jar包读取外部配置文件。案例: 项目工程名:auth -- 很明显,做鉴权使用的 项目配置文件:init.properties log4j.properties 项目引用jar包: lib/servlet-api.jar lib/log4j-1.2.15.jar lib/commons-collections-3.1.jar lib/commons-logging-1.0.4.jar lib/commons-pool.jar lib/ojdbc14.jar 读取配置文件示例: 目录结构如下:
解决方案I:自定义manifest.mf 文件 解释: Manifest-Version: 1.0 版本号,没啥特殊含义,但一定要有;Class-Path: 所有引用的jar包 注意: 每个“:”后面都要加空格,Class-Path中每个jar包间也加空格最后一行为空行 截图如下: b.通过Eclipse 到处jar包 右键项目工程----Export -- 选择Java下JAR File,下一步
件外部读取),选择导出jar包的位置; 注意:右侧的.classpath这些都不要选中,只把src下的java文件打包。
下一步 下一步:选中自定义的manifest.mf文件,完成 测试: 新建项目,导入刚刚生成的jar包和jar需要的所有包(把jar包所在工程lib下所有引用jar
java 文件流操作 2010-05-08 20:17:23| 分类:java SE | 标签:|字号大中小订阅 java中多种方式读文件 一、多种方式读文件内容。 1、按字节读取文件内容InputStream 读取的是字节 2、按字符读取文件内容InputStreamReader 读取的是字符 3、按行读取文件内容BufferredReader 可以读取行 4、随机读取文件内容 import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.io.Reader; public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。* @param fileName 文件的名 */ public static void readFileByBytes(String fileName){ File file = new File(fileName); InputStream in = null; try { System.out.println("以字节为单位读取文件内容,一次读一个字节:"); // 一次读一个字节 in = new FileInputStream(file); int tempbyte; while((tempbyte=in.read()) != -1){ System.out.write(tempbyte); } in.close(); } catch (IOException e) { e.printStackTrace(); return; } try { System.out.println("以字节为单位读取文件内容,一次读多个字节:"); //一次读多个字节
获取文本内容与读取文本指定行数内容浅析(java) 在此项目中直接套用以前工程中获取文本内容的方法发现一直提示“数组下标越界”,通过分析和查找得出以下心得: 获取文本内容: private static final String CHART_PATH ="D://data3"; public static void main(String[] args) throws RowsExceededException,WriteException, BiffException{ try { readFileByLines(CHART_PATH+".txt"); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } } public static void readFileByLines(String fileName) throws IOException,RowsExceededException,WriteException{ //打开文件 WritableWorkbook book = Workbook.createWorkbook( new File(CHART_PATH+".xls")); WritableSheet sheet = book.createSheet("看我", 0); //读取txt文件内容 File file = new File(fileName); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis,"GBK"); BufferedReader reader = null; try { reader = new BufferedReader(isr); String temString = null; //一次读入一行,以null结束 int i = 0; while((temString = reader.readLine())!= null){ System.out.println("+++++++"+temString); String[] str = temString.split(","); for(int j= 0;j package com.test; import java.io.File; import java.io.IOException; import java.io.InputStream; import https://www.wendangku.net/doc/3e14799909.html,.URL; import java.util.Properties; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class Test9 { public static void main(String[] args) throws IOException { String jarName="/test_p.jar";//Jar包所在的位置 String fileName="config/application.properties";//文件在jar包里的路径 String resource = Test9.class.getResource(jarName).getFile(); File file = new File(resource); JarFile jarFile = new JarFile(file);//读入jar文件 JarEntry entry = jarFile.getJarEntry(fileName); InputStream input = jarFile.getInputStream(entry);//读入需要的文件 Properties props = new Properties(); props.load(input); System.out.println(props.getProperty("Driver")); jarFile.close(); } } java对文件名的几个操作,获取文件扩展名,去掉扩展名 /** * Return the extension portion of the file's name . * * @see #getExtension */ public static String getExtension(File f) { return (f != null) ? getExtension(f.getName()) : ""; } public static String getExtension(String filename) { return getExtension(filename, ""); } public static String getExtension(String filename) { return getExtension(filename, ""); } public static String getExtension(String filename, String defExt) { if ((filename != null) && (filename.length() > 0)) { int i = https://www.wendangku.net/doc/3e14799909.html,stIndexOf('.'); if ((i >-1) && (i < (filename.length() - 1))) { return filename.substring(i + 1); } } return defExt; } public static String trimExtension(String filename) { if ((filename != null) && (filename.length() > 0)) { int i = https://www.wendangku.net/doc/3e14799909.html,stIndexOf('.'); if ((i >-1) && (i < (filename.length()))) { return filename.substring(0, i); } } return filename; } substring(参数)是java中截取字符串的一个方法 有两种传参方式 JS分段获取URL解析 URL : 统一资源定位符 (Uniform Resource Locator, URL) 完整的URL由这几个部分构成: scheme://host:port/path?query#fragment scheme = 通信协议 (常用的http,ftp,maito等) host = 主机 (域名或IP) port = 端口号 path = 路径 query = 查询 可选,用于给动态网页(如使用CGI、ISAPI、PHP/JSP/ASP/https://www.wendangku.net/doc/3e14799909.html,等技术制作的网页)传递参数,可有多个参数,用”&”符号隔开,每个参数的名和值用”=”符号隔开。 fragment = 信息片断 字符串,用于指定网络资源中的片断。例如一个网页中有多个名词解释,可使用fragment直接定位到某一名词解释。(也称为锚点.) 对于这样一个URL https://www.wendangku.net/doc/3e14799909.html,:80/seo/?ver=1.0&id=6#imhere 我们可以用javascript获得其中的各个部分 1, window.location.href 整个URl字符串(在浏览器中就是完整的地址栏) 2,window.location.protocol URL 的协议部分 本例返回值:http: 3,window.location.host URL 的主机部分 本例返回值:https://www.wendangku.net/doc/3e14799909.html, 4,window.location.port URL 的端口部分 如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符本例返回值:”" 5,window.location.pathname URL 的路径部分(就是文件地址) 本例返回值:/seo/ 6,window.location.search 查询(参数)部分 除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值本例返回值:?ver=1.0&id=6 7,window.location.hash 锚点 本例返回值:#imhere Java 读取上传文件里的数据,记事本文件和excel文件 本文,文本文件里的数据,每列以 Tab 分隔。 其它分隔符情况下,只需修改对分隔符的判断即可 本文是将文本文件或excel文件里的数据读到List 读取配置文件和修改配置文件(ServiceIP.properties)(原创) package espeed.util; import java.io.*; import java.util.Properties; /* * 配置短信服务器IP(配置文件建在SRC下,ServiceIP.properties) */ public class EditServiceIP { private static Properties properties=new Properties(); private static EditServiceIP esip; public EditServiceIP(){} public static EditServiceIP getInstance(){ if(esip==null) esip=new EditServiceIP(); return esip; } //取得短信服务器IP public String getSmsServiceIP(){ InputStream is=EditServiceIP.class.getClassLoader().getResourceAsSt ream("ServiceIP.properties"); try { properties.load(is); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("------------取得短信服务器IP地址发生IO异常"); } String provalue=properties.getProperty("SMS.ServiceIP"); return provalue; } //修改短信服务器IP public String modifySmsServieIP(String smsServiceIP){ File file=new File(EditServiceIP.class.getClassLoader().getResource("S erviceIP.properties").getPath()); try{ properties.load(new FileInputStream(file)); js下载文件的实现方法一 f8b js下载文件的实现方法及注意 js中实现文件下载 (一) 最简单的方式是在页上做超级链接如:<a href="music/abc.m3">下载</a>。 但是这样服务器上的目录资源会直接暴露给最终用户会给站带来一些不安全的因素。 因此可以采用其它方式实现下载可以采用: 1、RequestDisatcher的方式进行; 2、采用文件流输出的方式下载。(推荐) 1、采用RequestDisatcher的方式进行 Js代码 <% resonse.setContentTye("alication/x-download");//设置为下载alication/x-download String filedownload = "/要下载的文件名";//即将下载的文件的相对径 String filedislay = "最终要显示给用户的保存文件名";//下载文件时显示的文件保存名称 String filenamedislay = URLEncoder.encode(filedislay,"UTF-8"); resonse.addHeader("Content-Disosition","attachment;filena me=" + filedislay); try { RequestDisatcher dis = alication.getRequestDisatcher(filedownload); 1、按字节读取文件内容 2、按字符读取文件内容 3、按行读取文件内容 4、随机读取文件内容 public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 */ public static void readFileByBytes(String fileName) { File file = new File(fileName); InputStream in = null; try { System.out.println("以字节为单位读取文件内容,一次读一个字节:"); // 一次读一个字节 in = new FileInputStream(file); int tempbyte; while ((tempbyte = in.read()) != -1) { System.out.write(tempbyte); } in.close(); } catch (IOException e) { e.printStackTrace(); return; } try { System.out.println("以字节为单位读取文件内容,一次读多个字节:"); // 一次读多个字节 byte[] tempbytes = new byte[100]; int byteread = 0; in = new FileInputStream(fileName); ReadFromFile.showAvailableBytes(in); // 读入多个字节到字节数组中,byteread为一次读入的字节数 while ((byteread = in.read(tempbytes)) != -1) { System.out.write(tempbytes, 0, byteread); } 项目中一个需求就是所有的功能都是插件的形式装入系统,这就需要利用Spring去动态加载某一位置下的配置文件,就总结了下Spring中加载xml配置文件的方式, xml是最常见的spring 应用系统配置源。Spring中的几种容器都支持使用xml装配bean,包括:XmlBeanFactory, ClassPathXmlApplicationContext, FileSystemXmlApplicationContext, XmlWebApplicationContext, ..... 一: XmlBeanFactory 引用资源 1.Resource cr = new ClassPathResource("applicationContext.xml"); BeanFactory bf=new XmlBeanFactory(cr); UserDao userDao = (UserDao)bf.getBean("userDao"); 二: ClassPathXmlApplicationContext 编译路径 使用ClassPathXmlApplicationContext对象获取,必须把applicationContext.xml放置到类的加载路径中,也就是Src下面 1.ApplicationContext factory=new ClassPathXmlApplicationContext("classpath:appcontext.xml"); // src目录下的 2.ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao userDao = (UserDao)context.getBean("userDao"); 3.ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext-oracle.xml","applicationContext.xml"}); UserDao userDao = (UserDao)context.getBean("userDao"); // src/conf 目录下的 4.ApplicationContext factory=new ClassPathXmlApplicationContext("conf/appcontext.xml"); 5.ApplicationContext factory=new ClassPathXmlApplicationContext("file:G:/Test/src/appcontext.xml"); 三: FileSystemXmlApplicationContext用文件系统 jquery.js文件报错-解决方法 tomcat首页报Directory listing for错误, eclipse启动tomcat,首页报404错误 引入一个正常的新项目后,eclipse报错: 一、jQuery.js文件报错 解决办法: 1.window-preferences-中将JavaScript -validator-erros warnings取消 2.将eclipse工作空间中的当前项目的.project文件中的 JAVA读取jar包内部配置文件
java对文件名的几个操作,获取文件扩展名,去掉扩展名
JS分段获取URL解析
java读取上传excel文件和txt文件中的数据
读取配置文件和修改配置文件(ServiceIP.properties)(原创)
js下载文件的实现方法一
java文件读写代码
Spring中加载xml配置文件的几种方式
jquery.js文件报错-解决方法
Java流 一、流的分类 ?按数据流动方向 –输入流:只能从中读取字节数据,而不能向其写出数据 –输出流:只能向其写入字节数据,而不能从中读取数据?按照流所处理的数据类型 –字节流:用于处理字节数据。 –字符流:用于处理Unicode字符数据。 ?按照流所处理的源 –节点流:从/向一个特定的IO设备读/写数据的流。(低级流)–处理流:对已存在的流进行连接和封装的流。(高级流)二、缓冲流 ?缓冲流要“套接”在相应的节点流之上,对读写的数据提供了缓冲的功能,提高了读写的效率,同时增加了一些新的方法。 ?J2SDK提供了四种缓存流: –BufferedReader –BufferedWriter –BufferedInputStream s –BufferedOutputStream
?缓冲输入流支持其父类的mark()和reset()方法: –mark()用于“标记”当前位置,就像加入了一个书签,可以使用reset()方法返回这个标记重新读取数据。?BufferedReader提供了readLine()方法用于读取一行字符串(以\r 或\n分隔)。 ?BufferedWriter提供了newLine()用于写入一个行分隔符。 ?对于输出的缓冲流,写出的数据会先在内存中缓存,使用flush()方法将会使内存中的数据立刻写出。 三、类层次 3.1、InputStream类层次
3.2、OutputStream类层次 3.3、Reader类层次
3.4、Writer类层次 四、常用的字符流与字节流的转化 说明: 1.字节流用于读写诸如图像数据之类的原始字节流。 2.字符流用于读写诸如文件数据之类的字符流。 3.低级流能和外设交流。 4.高级流能提高效率。 5.InputStreamReader 是字节流通向字符流的桥梁。 6.OutputStreamWriter 是字符流通向字节流的桥梁。
一. 创建文件 (1)最常用的(获得一个固定路径下的文件对象) File parentFile = new File(“D:\\My Documents\\.....”);//参数是一个路径的字符串。 (2)在父目录创建一个名为child的文件对象,child 为文件对象的名字 File chileFile= new File(“D:\\My Documents\\.....”,String child); 或File chileFile= new File(parentFile,String child); 二,常见文件夹属性和方法 (1)createNewFile(); 该方法的作用是创建指定的文件。该方法只能用于创建文件,不能用于创建文 件夹,且文件路径中包含的文件夹必须存在 File file=new ("D:\\My Document\\text.txt"); file.createNewFile(); 这样就会在D盘下的My Document 创建text.txt的记事本(注意:首先得保 证D盘下有My Documen这个文件夹) (2)mkdir(); 根据File对象的名字(路径)创建一个目录(文件夹),如果是相对目录,则新建的目
录在当前目录下 (3)mkdirs(); 如果File对象名字有多级目录,则可以调用该方法一次性创建多级目录。 (4)exists(); 判断File对象指向的文件是否存在,返回一个boolean类型(5)isDirectory(); 判断File对象指向的文件是否为目录,返回一个boolean类型的值,true或者false。 (6)getName();获得文件名称(不带路径) (7)length(); 得到File对象指向文件的长度,以字节计算,返回一个长整形的值(long);注意:在 系统中,文件夹(目录)的大小为零,也就是不占用空间,使用length()时返回的是0 (8)delete(); 删除File对象所指定的文件 (9)isFile(); 判断File对象指向的文件是不是标准文件(就像图片,音乐文件等) 三,文件的属性和方法 1.File.separator 当前操作系统的名称分隔符,等于字符串“\”.
spring 框架的xml文件如何读取properties文件数据 第一步:在spring配置文件中 注意:value可以多配置几个properties文件
js取得当前url,javascript获取当前页面url值,js获取域名- js取得当前url,javascript获取当前页面url值,js获取域名 分类:JS 2010-09-01 14:14 如果获取“当前”域名 host = window.location.host; url=document.domain; url = window.location.href; 取得完整url路径: 用以下代码可以完整研证结果: thisDLoc = document.location; thisURL = document.URL; thisHREF = document.location.href; thisSLoc = self.location.href; thisTLoc = top.location.href; thisPLoc = parent.document.location; thisTHost = top.location.hostname;
thisHost = location.hostname; 还有一种稍有些复杂的取域名的方法,也是过滤了文件夹名,文件名,参数 …… var getHost = function(url) { var host = "null"; if(typeof url == "undefined"|| null == url) { url = window.location.href; } var regex = /.*\:\/\/([^\/]*).*/; var match = url.match(regex); if(typeof match != "undefined" && null != match) { host = match[1]; } return host; }
1.保存对象到文件中 Java语言只能将实现了Serializable接口的类的对象保存到文件中,利用如下方法即可: public static void writeObjectToFile(Object obj) { File file =new File("test.dat"); FileOutputStream out; try { out = new FileOutputStream(file); ObjectOutputStream objOut=new ObjectOutputStream(out); objOut.writeObject(obj); objOut.flush(); objOut.close(); System.out.println("write object success!"); } catch (IOException e) { System.out.println("write object failed"); e.printStackTrace(); } } 参数obj一定要实现Serializable接口,否则会抛出 java.io.NotSerializableException异常。另外,如果写入的对象是一个容器,例如List、Map,也要保证容器中的每个元素也都是实现了Serializable 接口。例如,如果按照如下方法声明一个Hashmap,并调用writeObjectToFile方法就会抛出异常。但是如果是 Hashmap
Java IO流和文件操作Java流操作有关的类或接口: Java流类图结构:
1、File类 File类是对文件系统中文件以及文件夹进行封装的对象,可以通过对象的思想来操作文件和文件夹。 File类保存文件或目录的各种元数据信息,包括文件名、文件长度、最后修改时间、是否可读、获取当前文件的路径名,判断指定文件是否存在、获得当前目录中的文件列表,创建、删除文件和目录等方法。 构造方法摘要 File(File parent, String child) File(String pathname) File(String parent, String child) 构造函数 创建方法 1.boolean createNewFile() 不存在返回true 存在返回false 2.boolean mkdir() 创建目录 3.boolean mkdirs() 创建多级目录 删除方法 1.boolean delete() 2.boolean deleteOnExit() 文件使用完成后删除 例子1:列出指定文件夹的文件或文件夹 public class FileDemo1 { public static void main(String[] args){ File[] files =File.listRoots(); for(File file:files){
System.out.println(file); if(file.length()>0){ String[] filenames =file.list(); for(String filename:filenames){ System.out.println(filename); } } } } } 例子2:文件过滤 import java.io.File; public class FileTest2 { public static void main(String[] args) { File file = new File("file"); String[] names = file.list(); for(String name : names) { if(name.endsWith(".java")) { System.out.println(name); }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
选择导入数据源: |