浏览 1797 次
精华帖 (0) :: 良好帖 (1) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2010-07-12
最后修改:2011-06-10
转载请注明出处: 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: ");
system.out重定位方法: System.setOut() //注意先把之前的System.out保存起来,然后重定向使用完毕之后再恢复回去!! 同理,还可以设置System.err ,System.in这两个IO流的默认设置. 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |