java读写Properties属性文件公用方法
在Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。
Properties提供了如下几个主要的方法:
1.getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数key ,得到key 所对应的value。
2.load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(如test.properties 文件)进行装载来获取该文件中的所有键- 值对。以供getProperty ( String key) 来搜索。
3.setProperty ( String key, String value) ,调用Hashtable 的方法put 。他通过调用基类的put方法来设置键- 值对。
4.store ( OutputStream out, String comments),以适合使用load 方法加载到Properties 表中的格式,将此Properties 表中的属性列表(键和元素对)写入输出流。与load 方法相反,该方法将键- 值对写入到指定的文件中去。
5.clear (),清除所有装载的键- 值对。该方法在基类中提供。
以下提供一套读写配置文件的公用实用方法,我们以后可以在项目中进行引入。
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import org.apache.log4j.Logger;
public class PropertieUtil {
//设置日志
private static Logger logger=Logger.getLogger(PropertieUtil.class);
private PropertieUtil() {
}
/**
* 读取配置文件某属性
*/
public static String readValue(String filePath,String key) {
Properties props=new Properties();
try {
if(filePath.startsWith("/")) {
filePath="/"+filePath;
}
InputStream in=PropertieUtil.class.getResourceAsStream(filePath);
props.load(in);
String value=props.getProperty(key);
return value;
} catch (IOException e) {
// TODO Auto-generated catch block
logger.error(e);
return null;
}
}
/**
* 打印配置文件全部内容
*/
public static void readProperties(String filePath) {
Properties props=new Properties();
try {
if(!filePath.startsWith("/")) {
filePath="/"+filePath;
}
InputStream in=PropertieUtil.class.getResourceAsStream(filePath);
props.load(in);
Enumeration> en=props.propertyNames();
//遍历打印
while(en.hasMoreElements()) {
String key=(String)en.nextElement();
String property=props.getProperty(key);
//日志信息显示键和值
https://www.wendangku.net/doc/6c8489022.html,(key+":"+property);
}
}catch(Exception e) {
//日志显示错误信息
logger.error(e);
}
}
最后测试效果如下:
调用:readProperties("jdbc.properties");
调用writeProperties("test.properties","test","test");
项目中,经常把一部分功能独立出来,做一个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/6c8489022.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/6c8489022.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/6c8489022.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/6c8489022.html,等技术制作的网页)传递参数,可有多个参数,用”&”符号隔开,每个参数的名和值用”=”符号隔开。 fragment = 信息片断 字符串,用于指定网络资源中的片断。例如一个网页中有多个名词解释,可使用fragment直接定位到某一名词解释。(也称为锚点.) 对于这样一个URL https://www.wendangku.net/doc/6c8489022.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/6c8489022.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 + "/"; %>
选择导入数据源: |