- 浏览: 234625 次
- 性别:
- 来自: 上海
博客专栏
-
Java应用集锦
浏览量:22395
文章分类
最新评论
-
yipeng_666:
yipeng_666 写道楼主可以分享源码吗 , 感激不尽邮 ...
基于jquery框架dwz做的后台管理系统 -
yipeng_666:
楼主可以分享源码吗 , 感激不尽
基于jquery框架dwz做的后台管理系统 -
ughome:
楼主,能发个源码吗,我删除后刷新有问题,总是跳转到第一页。查询 ...
基于jquery框架dwz做的后台管理系统 -
ellie_it:
DWZ研究中,楼主可以分享源码学习下吗?万分感谢! 93020 ...
基于jquery框架dwz做的后台管理系统 -
hongshenghome:
前辈,dwz刚开始学,给我发份源码,万分感谢!!!!!,邮箱 ...
基于jquery框架dwz做的后台管理系统
转载请注明出处: http://renjie120.iteye.com/
使用java的一些知识的整理,以后在这里方便经常查找.
本文涉及如下四个方面:
1.不借助其他包,对xml文件的解析
2.java序列化和反序列化
3.读取java的property属性配置文件
4.常见IO方法搜集
1.不借助其他包,对xml文件的解析
import java.io.FileInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class DomUtil { protected static Log log = LogFactory.getLog("DomUtil"); public static void main(String args[]) { Document doc; Element root; String elementname; String filename; try { filename = System.getProperty("user.dir"); filename = filename + "/WebRoot/WEB-INF/classes/struts.xml"; doc = getXmlDocument(filename); // 获取xml文档的根节点 // root = getRoot(doc); // System.out.println(root.getElementsByTagName("action").getLength()); // elementname = root.getNodeName();//获得根节点名称 // System.out.println("输出根节点名称:" + elementname); // 打印根节点的属性和值 // printAllAttributes(root); // 打印该文档全部节点 // System.out.println("打印全部节点"); // printElement(root, 0); NodeList packages = doc.getElementsByTagName("package"); if (packages != null && packages.getLength() > 0) { for (int i = 0; i < packages.getLength(); i++) { Node _package = packages.item(i); NodeList actions = _package.getChildNodes(); for (int j = 0; j < actions.getLength(); j++) { Node _action = actions.item(j); if (_action.getNodeName().equals("action")) { if (getAttribute(_action,"name").equals("hello")) { NodeList results = _action.getChildNodes(); for (int k = 0; k < results.getLength(); k++) { Node _result = results.item(k); if(_result.getNodeName().equals("result")&&getAttribute(_result,"name").equals("success")) System.out.println(_result.getTextContent()); } } } } } } } catch (Exception exp) { exp.printStackTrace(); } } /** * 得到文档对象的根节点. * @param doc 文档对象 * @return */ public static Element getRoot(Document doc){ return doc.getDocumentElement(); } /** * 得到指定节点的指定属性值. * @param node * @param attrName * @return */ public static String getAttribute(Node node,String attrName){ if(node.hasAttributes()){ Node _node = node.getAttributes().getNamedItem(attrName); if(_node!=null) return _node.getNodeValue(); else{ return ""; } } else return ""; } /** * 得到指定节点的文本内容. * @param node * @return */ public static String getText(Node node){ return node.getTextContent(); } /** * 根据xml文件地址得到xml对象. * @param fileName xml地址 * @return */ public static Document getXmlDocument(String fileName){ Document doc = null; DocumentBuilderFactory factory; DocumentBuilder docbuilder; FileInputStream in; try { in = new FileInputStream(fileName); // 解析xml文件,生成document对象 factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); docbuilder = factory.newDocumentBuilder(); doc = docbuilder.parse(in); } catch (Exception e) { log.error("DomUtil---getXmlDocument", e); } return doc; } /** * 根据xml文件流地址得到xml对象. * @param in * @return */ public static Document getXmlDocument(InputStream in){ Document doc = null; DocumentBuilderFactory factory; DocumentBuilder docbuilder; try { // 解析xml文件,生成document对象 factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); docbuilder = factory.newDocumentBuilder(); doc = docbuilder.parse(in); } catch (Exception e) { log.error("DomUtil---getXmlDocument", e); } return doc; } /** * 打印指定节点的全部属性. * @param elem 节点对象 */ public static void printAllAttributes(Element elem) { NamedNodeMap attributes;//根节点所有属性 int i, max; String name, value; Node curnode; attributes = elem.getAttributes(); max = attributes.getLength(); for (i = 0; i < max; i++) { curnode = attributes.item(i); name = curnode.getNodeName(); value = curnode.getNodeValue(); System.out.println("输出节点名称和值:" + name + " = " + value); } } /** * 得到指定节点的所有属性,返回结果是一个map对象. * @param elem 节点对象 * @return */ public static Map getAllAttributes(Element elem) { Map map = new HashMap(); NamedNodeMap attributes;//根节点所有属性 int i, max; String name, value; Node curnode; attributes = elem.getAttributes(); max = attributes.getLength(); for (i = 0; i < max; i++) { curnode = attributes.item(i); name = curnode.getNodeName(); value = curnode.getNodeValue(); map.put(name, value); } return map; } /** * 打印节点的所有节点的名称和值. * @param elem 节点对象 * @param depth 深度 */ public static void printElement(Element elem, int depth) { String elementname; NodeList children; int i, max; Node curchild; Element curelement; String nodename, nodevalue; // elementname = elem.getnodename(); // 获取输入节点的全部子节点 children = elem.getChildNodes(); // 按一定格式打印输入节点 for (int j = 0; j < depth; j++) { //System.out.print(" "); } printAllAttributes(elem); // 采用递归方式打印全部子节点 max = children.getLength(); System.out.println("输出子节点的长度:" + elem.getNodeName() + ":::" + max); //输出全部子节点 for (int j = 0; j < max; j++) { System.out.println("tt:" + children.item(j)); } for (i = 0; i < max; i++) { curchild = children.item(i); // 递归退出条件 if (curchild instanceof Element) { curelement = (Element) curchild; printElement(curelement, depth + 1); } else { nodename = curchild.getNodeName(); nodevalue = curchild.getNodeValue(); for (int j = 0; j < depth; j++) { System.out.print(" "); System.out.println(nodename + " = " + nodevalue); } } } } }
2.java序列化和反序列化
/** * 序列化对象保存到本地文件. * @param obj 对象 * @param fileName 文件名 */ public static void saveObjectToFile(Object obj, String fileName) { try { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(fileName)); out.writeObject(obj); out.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 反序列化. * @param fileName 加载对象的文件名 * @return */ public static Object getObjectFromFile(String fileName){ Object result = new Object(); try { ObjectInputStream in = new ObjectInputStream(new FileInputStream( fileName)); result = in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } return result; }
3.java读取属性文件:
private static final String CONFIG_FILE="/application.properties"; private static Properties prop; private static File mFile; static { // getResourceAsStream的参数"/application.properties"表示以当前类的包的根路径为基准路径 InputStream inputStream = ConfigHelper.class.getResourceAsStream(CONFIG_FILE); prop = new Properties(); try { prop.load(inputStream); inputStream.close(); } catch (IOException e) { System.out.println("获取系统属性文件异常:"); } } /** * 根据key获取属性培植文件中对应的value * @param key * @return */ public static String getProperty(String key){ String value = prop.getProperty(key); try{ value = new String(value.getBytes("ISO-8859-1"),"GBK"); }catch(UnsupportedEncodingException e){ System.out.println (e.getMessage()); } return value; }
下面是更加详尽的六种方式:
1。使用java.util.Properties类的load()方法 示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name)); Properties p = new Properties(); p.load(in); 2。使用java.util.ResourceBundle类的getBundle()方法 示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault()); System.out.println(rb.getString("mailServer")); 3。使用java.util.PropertyResourceBundle类的构造函数 示例: InputStream in = new BufferedInputStream(new FileInputStream(name)); ResourceBundle rb = new PropertyResourceBundle(in); 4。使用class变量的getResourceAsStream()方法 示例: InputStream in = JProperties.class.getResourceAsStream(name); Properties p = new Properties(); p.load(in); 5。使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法 示例: InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name); Properties p = new Properties(); p.load(in); 6。使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法 示例: InputStream in = ClassLoader.getSystemResourceAsStream(name); Properties p = new Properties(); p.load(in);
4.下面和IO相关:
/** * 删除一个文件. * @param filename 文件名. * @throws IOException */ public static void deleteFile(String filename){ File file = new File(filename); file.deleteOnExit(); } /** * 复制文件. * @param srcFileName * @param desFileName */ public static void copyFile(String srcFileName, String desFileName) { try { FileChannel srcChannel = new FileInputStream(srcFileName) .getChannel(); FileChannel dstChannel = new FileOutputStream(desFileName) .getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 对指定文件添加字符串内容. * @param fileName * @param contant */ public static void appendToFile(String fileName, String contant) { PrintWriter out; try { out = new PrintWriter(new BufferedWriter(new FileWriter(fileName,true))); out.print(contant); out.close(); } catch (IOException e) { System.out.println("读写文件出现异常!"); } catch (Exception e) { System.out.println("出现异常"); } } /** * 读取文件为字节数组 * @param filename * @return * @throws IOException */ public static byte[] readFile(String filename) throws IOException { File file = new File(filename); if (filename == null || filename.equals("")) { throw new NullPointerException("无效的文件路径"); } long len = file.length(); byte[] bytes = new byte[(int) len]; BufferedInputStream bufferedInputStream = new BufferedInputStream( new FileInputStream(file)); int r = bufferedInputStream.read(bytes); if (r != len) throw new IOException("读取文件不正确"); bufferedInputStream.close(); return bytes; } /** * 将字节数组写入文件 * @param data byte[] * @throws IOException */ public static void writeFile(byte[] data, String filename) throws IOException { File file = new File(filename); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream( new FileOutputStream(file)); bufferedOutputStream.write(data); bufferedOutputStream.close(); } /** * 将字符数组转换为字节数组 * @param chars * @return */ public byte[] getBytes(char[] chars) { Charset cs = Charset.forName("UTF-8"); CharBuffer cb = CharBuffer.allocate(chars.length); cb.put(chars); cb.flip(); ByteBuffer bb = cs.encode(cb); return bb.array(); } /** * 字节数组转换为字符数组 * @param bytes * @return */ public char[] getChars(byte[] bytes) { Charset cs = Charset.forName("UTF-8"); ByteBuffer bb = ByteBuffer.allocate(bytes.length); bb.put(bytes); bb.flip(); CharBuffer cb = cs.decode(bb); return cb.array(); } /** * 读取指定文件的内容,返回文本字符串 * @param fileName 文件名 * @param linkChar 换行符号 * @return */ public static String readFile(String fileName, String linkChar) { StringBuffer sb = new StringBuffer(); BufferedReader in; String result = ""; try { // 定义文件读的数据流 in = new BufferedReader(new FileReader(fileName)); String s; while ((s = in.readLine()) != null) { sb.append(s); // 换行符号默认是13!! if (linkChar == null || "".equals(linkChar)) sb.append((char) 13); else sb.append(linkChar); } in.close(); int i = linkChar.length(); result = sb.toString(); result = result.subSequence(0, sb.length() - i).toString(); } catch (FileNotFoundException e) { System.out.println("找不到文件" + fileName + "!"); throw new Exception("文件找不到!"); } catch (IOException e) { System.out.println("出现异常!"); throw new Exception("文件找不到!"); } catch (Exception e) { e.printStackTrace(); System.out.println("出现异常!"); throw new Exception("文件找不到!"); } finally { return result; } } /** * 将指定文件中的内容已每行转换为字符串数组 * @param fileName * @return */ public static String[] readFileToStrArr(String fileName) { BufferedReader in; ArrayList list = new ArrayList(); String[] result = null; try { // 定义文件读的数据流 in = new BufferedReader(new FileReader(fileName)); String s; while ((s = in.readLine()) != null) { list.add(s); } result = new String[list.size()]; Iterator it = list.iterator(); int index = 0; while (it.hasNext()) { result[index++] = it.next().toString(); } return result; } catch (FileNotFoundException e) { System.out.println("找不到文件!"); throw new Exception("文件找不到!"); } catch (IOException e) { System.out.println("出现异常!"); throw new Exception("文件找不到!"); } finally { return result; } } /** * 将字符串写进文件 * @param fileName 文件名 * @param contant 要写入文件的字符串 */ public static void writeFile(String fileName, String contant) { PrintWriter out; try { out = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); out.print(contant); out.close(); } catch (IOException e) { System.out.println("读写文件出现异常!"); } catch (Exception e) { System.out.println("出现异常"); } } /** * 字符串转换为字符数组 * @param str * @return */ public static char[] strToChars(String str) { try { byte[] temp; temp = str.getBytes(System.getProperty("file.encoding")); int len = temp.length; char[] oldStrbyte = new char[len]; for (int i = 0; i < len; i++) { char hh = (char) temp[i]; if (temp[i] < 0) { hh = (char) (temp[i] + 256); } oldStrbyte[i] = hh; } return oldStrbyte; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
下面是一些零散的知识点:::
得到控制台的输入字符串:
BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(new BufferedInputStream(System.in)));
System.out.print("\nEnter your regex: ");
String s = bufferedreader.readLine();
system.out重定位方法:
System.setOut() //注意先把之前的System.out保存起来,然后重定向使用完毕之后再恢复回去!!
同理,还可以设置System.err ,System.in这两个IO流的默认设置.
发表评论
-
test
2018-02-01 15:19 0testtesttesttest -
spring中使用AOP进行日志记录[含代码]
2017-09-13 15:14 731spring的IOC和AOP是说的最烂的东西,尤其是后者, ... -
关于java web开发中的很多小问题集锦
2017-05-11 11:24 19751、导出excel文件,文件名的中文问题 public ... -
自定义java类重写hashcode和equals方法
2014-12-24 15:34 12241.何时需要重写equals() 当一个类有自 ... -
java的普通类重写hashcode和equals方法
2014-12-24 15:33 0class AddServe { public Stri ... -
解决问题
2013-11-18 22:54 1364启动tomcat的时候,报错如下: java 写道 严 ... -
强烈推荐一个简单而实用的数据库连接池工程
2013-07-15 23:53 1064接触过很多的数据库连接池,有d3p0,druid,都比较nb ... -
自己写的一个jedis操作模板类
2013-07-15 23:28 1361jedis是java的redis客户端程序,在spring下 ... -
打算写一个关于股票的开源小玩意
2013-03-08 23:44 0目标: 1.锻炼自己的编码能力,组织代码的能力 2.为 ... -
java应用集锦9:httpclient4.2.2的几个常用方法,登录之后访问页面问题,下载文件
2012-11-16 16:03 19889转账注明出处:http://renjie120.iteye. ... -
java应用集锦8:使用poi进行excel操作,同时支持excel2003和2007
2011-06-21 21:42 6385下面的这段代码仅仅支持excel2003,要同时支持2007和 ... -
java应用集锦7:日期函数 double精度问题 list和数组等
2010-07-20 17:51 2406转载请注明出处: http://renjie120.itey ... -
java应用集锦6:字符串base64加密解密 MD5加密
2010-07-20 16:56 5545转载请注明出处: http://renjie120.it ... -
java应用集锦5:缓存管理 单例模式 ThreadLocal
2010-07-20 12:06 6377转载请注明出处: http://renjie120.it ... -
java应用集锦4:保存大对象 上传显示进度条
2010-07-20 11:20 3419转载请注明出处: http://renjie120.it ... -
java应用集锦3:正则表达式 excel操作之jxl
2010-07-13 17:20 3240转载请注明出处: http://renjie120.it ... -
java应用集锦2:反射
2010-07-07 17:52 1831在项目中多处使用到反射方法,jdk为1.5.现总结如下: 1 ... -
制作可以执行的jar包
2010-06-08 13:41 1186今天试了一下制作可执行的Jar文件的方法。 具体如下: 首 ... -
Cannot load JDBC driver class 'oracle.jdbc.driver.OracleDriver'的解决办法
2010-04-29 11:55 8589exception javax.servlet. ...
相关推荐
Java面试题集锦6:华为面试题 管理资料.pdfJava面试题集锦6:华为面试题 管理资料.pdfJava面试题集锦6:华为面试题 管理资料.pdfJava面试题集锦6:华为面试题 管理资料.pdfJava面试题集锦6:华为面试题 管理资料.pdf...
Java常见问题集锦 Java常见问题集锦Java常见问题集锦
JAVA案例开发集锦:分六个压缩卷,请都下载了再解压 第一压缩卷 下完后请把文件名改为:JAVA案例开发集锦[1].part1.rar.rar
如何设置Java 2(JDK1.2)的环境变量? 答: Java 2安装后,需要设置PATH和JAVA_HOME环境变量.与JDK1.1不同的是:设置好JAVA_HOME环境变量后,JVM将自动搜索系统类库以及用户的当前路径. Java 2环境变量的设置如下例所示...
Java笔试题集锦/JAVA 基础/servlet笔试题目
Java常见问题集锦,包括安装环境、代码常见问题等
Java 面试 最新 最全 算法 框架 语言;core java career essentials,542页完整版
java常见错误集锦,这里讲java开发中常见的问题都汇集了起来,希望对学java的同学有帮助
Java编程精选集锦
如何设置Java 2(JDK1.2)的环境变量? 答: Java 2安装后,需要设置PATH和JAVA_HOME环境变量.与JDK1.1不同的是:设置好JAVA_HOME环境变量后,JVM将自动搜索系统类库以及用户的当前路径. Java 2环境变量的设置如下例所示: ...
JAVA FAQ Java常见问题集锦
Java经典项目集锦
该光盘中有《Java案例开发集锦》一书中的所有案例源程序代码,编译通过的实例类代码和工程文件,以及案例中应用的数据库,并有在案例中涉及的相关Java类文件。配书光盘中全部内容包括: 1. chp1-chp10目录。分别...
java面试题集锦.pdf 、 Core Java : 基础及语法: 异常: 集合: 线程: IO & Socket : 、 OOAD & UML : 、 XML : 、 SQL : 、 JDBC & Hibernate : 、 Web : 、 EJB & Spring : 、数据结构 & 算法 & 计算机...
JAVA精华集锦.JAVA精华集锦.JAVA精华集锦.JAVA精华集锦.JAVA精华集锦.JAVA精华集锦.