序列化 操作xml 常见IO

使用java的一些知识的整理,以后在这里方便经常查找.

本文涉及如下四个方面:

1.不借助其他包,对xml文件的解析

2.java序列化和反序列化

3.读取java的property属性配置文件

4.常见IO方法搜集

 

1.不借助其他包,对xml文件的解析

 

  1 import java.io.FileInputStream;
  2 import java.io.InputStream;
  3 import java.util.HashMap;
  4 import java.util.Map;
  5 
  6 import javax.xml.parsers.DocumentBuilder;
  7 import javax.xml.parsers.DocumentBuilderFactory;
  8 
  9 import org.apache.commons.logging.Log;
 10 import org.apache.commons.logging.LogFactory;
 11 import org.w3c.dom.Document;
 12 import org.w3c.dom.Element;
 13 import org.w3c.dom.NamedNodeMap;
 14 import org.w3c.dom.Node;
 15 import org.w3c.dom.NodeList;
 16 
 17 public class DomUtil {
 18     protected static Log log = LogFactory.getLog("DomUtil");
 19     public static void main(String args[]) {
 20         Document doc;
 21         Element root;
 22         String elementname;
 23         String filename;
 24         try {
 25             filename = System.getProperty("user.dir");
 26             filename = filename + "/WebRoot/WEB-INF/classes/struts.xml";
 27 
 28             doc = getXmlDocument(filename);
 29             // 获取xml文档的根节点
 30             // root = getRoot(doc);
 31             // System.out.println(root.getElementsByTagName("action").getLength());
 32             // elementname = root.getNodeName();//获得根节点名称
 33             // System.out.println("输出根节点名称:" + elementname);
 34             // 打印根节点的属性和值
 35             // printAllAttributes(root);
 36             // 打印该文档全部节点
 37             // System.out.println("打印全部节点");
 38             // printElement(root, 0);
 39             NodeList packages = doc.getElementsByTagName("package");
 40             if (packages != null && packages.getLength() > 0) {
 41                 for (int i = 0; i < packages.getLength(); i++) {
 42                     Node _package = packages.item(i);
 43                     NodeList actions = _package.getChildNodes();
 44                     for (int j = 0; j < actions.getLength(); j++) {
 45                         Node _action = actions.item(j);
 46                         if (_action.getNodeName().equals("action")) {
 47                             if (getAttribute(_action,"name").equals("hello")) {
 48                                 NodeList results = _action.getChildNodes();
 49                                 for (int k = 0; k < results.getLength(); k++) {
 50                                     Node _result = results.item(k);
 51                                     if(_result.getNodeName().equals("result")&&getAttribute(_result,"name").equals("success"))
 52                                     System.out.println(_result.getTextContent());
 53                                 }
 54                             }
 55                         }
 56                     }
 57                 }
 58             }
 59         } catch (Exception exp) {
 60             exp.printStackTrace();
 61         }
 62     }
 63 
 64     /**
 65      * 得到文档对象的根节点.
 66      * @param doc 文档对象
 67      * @return
 68      */
 69     public static Element getRoot(Document doc){
 70         return doc.getDocumentElement();
 71     }
 72     
 73     /**
 74      * 得到指定节点的指定属性值.
 75      * @param node
 76      * @param attrName
 77      * @return
 78      */
 79     public static String getAttribute(Node node,String attrName){
 80         if(node.hasAttributes()){
 81             Node _node = node.getAttributes().getNamedItem(attrName);
 82             if(_node!=null)
 83                 return _node.getNodeValue();
 84             else{
 85                 return "";
 86             }
 87         }
 88         else
 89             return "";
 90     }
 91     
 92     /**
 93      * 得到指定节点的文本内容.
 94      * @param node
 95      * @return
 96      */
 97     public static String getText(Node node){
 98         return node.getTextContent();
 99     }
100     
101     /**
102      * 根据xml文件地址得到xml对象.
103      * @param fileName xml地址
104      * @return
105      */
106     public static Document getXmlDocument(String fileName){
107         Document doc = null;
108         DocumentBuilderFactory factory;
109         DocumentBuilder docbuilder;
110 
111         FileInputStream in;
112         try {
113             in = new FileInputStream(fileName);
114             // 解析xml文件,生成document对象
115             factory = DocumentBuilderFactory.newInstance();
116             factory.setValidating(false);
117             docbuilder = factory.newDocumentBuilder();
118             doc = docbuilder.parse(in);            
119         } catch (Exception e) {
120             log.error("DomUtil---getXmlDocument", e);
121         }
122         return doc;
123     }
124     
125     /**
126      *  根据xml文件流地址得到xml对象.
127      * @param in
128      * @return
129      */
130     public static Document getXmlDocument(InputStream in){
131         Document doc = null;
132         DocumentBuilderFactory factory;
133         DocumentBuilder docbuilder;
134         try {
135             // 解析xml文件,生成document对象
136             factory = DocumentBuilderFactory.newInstance();
137             factory.setValidating(false);
138             docbuilder = factory.newDocumentBuilder();
139             doc = docbuilder.parse(in);            
140         } catch (Exception e) {
141             log.error("DomUtil---getXmlDocument", e);
142         }
143         return doc;
144     }
145     
146     /**
147      * 打印指定节点的全部属性.
148      * @param elem 节点对象
149      */
150     public static void printAllAttributes(Element elem) {
151         NamedNodeMap attributes;//根节点所有属性
152         int i, max;
153         String name, value;
154         Node curnode;
155 
156         attributes = elem.getAttributes();
157         max = attributes.getLength();
158 
159         for (i = 0; i < max; i++) {
160             curnode = attributes.item(i);
161             name = curnode.getNodeName();
162             value = curnode.getNodeValue();
163             System.out.println("输出节点名称和值:" + name + " = " + value);
164         }
165     }
166     
167     /**
168      * 得到指定节点的所有属性,返回结果是一个map对象.
169      * @param elem 节点对象
170      * @return 
171      */
172     public static Map getAllAttributes(Element elem) {
173         Map map = new HashMap();
174         NamedNodeMap attributes;//根节点所有属性
175         int i, max;
176         String name, value;
177         Node curnode;
178 
179         attributes = elem.getAttributes();
180         max = attributes.getLength();
181 
182         for (i = 0; i < max; i++) {
183             curnode = attributes.item(i);
184             name = curnode.getNodeName();
185             value = curnode.getNodeValue();
186             map.put(name, value);
187         }
188         return map;
189     }
190 
191     /**
192      * 打印节点的所有节点的名称和值.
193      * @param elem 节点对象
194      * @param depth 深度
195      */
196     public static void printElement(Element elem, int depth) {
197         String elementname;
198         NodeList children;
199         int i, max;
200         Node curchild;
201         Element curelement;
202         String nodename, nodevalue;
203 
204         // elementname = elem.getnodename();
205         // 获取输入节点的全部子节点
206         children = elem.getChildNodes();
207 
208         // 按一定格式打印输入节点
209         for (int j = 0; j < depth; j++) {
210             //System.out.print(" ");
211         }
212         printAllAttributes(elem);
213 
214         // 采用递归方式打印全部子节点
215         max = children.getLength();
216         System.out.println("输出子节点的长度:" + elem.getNodeName() + ":::" + max);
217         //输出全部子节点
218         for (int j = 0; j < max; j++) {
219             System.out.println("tt:" + children.item(j));
220         }
221 
222         for (i = 0; i < max; i++) {
223 
224             curchild = children.item(i);
225 
226             // 递归退出条件
227             if (curchild instanceof Element) {
228                 curelement = (Element) curchild;
229                 printElement(curelement, depth + 1);
230             } else {
231                 nodename = curchild.getNodeName();
232                 nodevalue = curchild.getNodeValue();
233 
234                 for (int j = 0; j < depth; j++) {
235                     System.out.print(" ");
236                     System.out.println(nodename + " = " + nodevalue);
237                 }
238             }
239         }
240     }
241 }

2.java序列化和反序列化

 1 /**
 2      * 序列化对象保存到本地文件.
 3      * @param obj 对象
 4      * @param fileName 文件名
 5      */
 6     public static void saveObjectToFile(Object obj, String fileName) {
 7         try {
 8             ObjectOutputStream out = new ObjectOutputStream(
 9                     new FileOutputStream(fileName));
10             out.writeObject(obj);
11             out.close();
12 
13         } catch (Exception e) {
14             e.printStackTrace();
15         }
16     }
17     
18     /**
19      * 反序列化.
20      * @param fileName 加载对象的文件名
21      * @return
22      */
23     public static Object getObjectFromFile(String fileName){
24         Object result = new Object();
25         try {
26             ObjectInputStream in = new ObjectInputStream(new FileInputStream(
27                     fileName));
28             result = in.readObject();
29             in.close();
30 
31         } catch (Exception e) {
32             e.printStackTrace();
33         }
34         return result;
35     }
36     

3.java读取属性文件:

 1     private static final String CONFIG_FILE="/application.properties";   
 2     private static Properties prop;   
 3     private static File mFile;   
 4        
 5 
 6      static {
 7         // getResourceAsStream的参数"/application.properties"表示以当前类的包的根路径为基准路径   
 8         InputStream inputStream = ConfigHelper.class.getResourceAsStream(CONFIG_FILE);
 9         prop = new Properties();
10         try {
11             prop.load(inputStream);
12             inputStream.close();
13         }
14         catch (IOException e) {
15             System.out.println("获取系统属性文件异常:");
16         }
17     }
18        
19     /**  
20      * 根据key获取属性培植文件中对应的value  
21      * @param key  
22      * @return  
23      */  
24     public static String getProperty(String key){   
25         String value = prop.getProperty(key);   
26         try{   
27             value = new String(value.getBytes("ISO-8859-1"),"GBK");   
28         }catch(UnsupportedEncodingException e){   
29             System.out.println (e.getMessage());   
30         }   
31         return value;   
32     }   

 下面是更加详尽的六种方式:

 1 1。使用java.util.Properties类的load()方法
 2 示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name));
 3 Properties p = new Properties();
 4 p.load(in);
 5 
 6 2。使用java.util.ResourceBundle类的getBundle()方法
 7 示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
 8          System.out.println(rb.getString("mailServer"));
 9 
10 3。使用java.util.PropertyResourceBundle类的构造函数
11 示例: InputStream in = new BufferedInputStream(new FileInputStream(name));
12 ResourceBundle rb = new PropertyResourceBundle(in);
13 
14 4。使用class变量的getResourceAsStream()方法
15 示例: InputStream in = JProperties.class.getResourceAsStream(name);
16 Properties p = new Properties();
17 p.load(in);
18 
19 5。使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
20 示例: InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
21 Properties p = new Properties();
22 p.load(in);
23 
24 6。使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法
25 示例: InputStream in = ClassLoader.getSystemResourceAsStream(name);
26 Properties p = new Properties();
27 p.load(in);

4.下面和IO相关:

  1       /**
  2      * 删除一个文件.
  3      * @param filename 文件名.
  4      * @throws IOException
  5      */
  6     public static void deleteFile(String filename){
  7         File file = new File(filename); 
  8         file.deleteOnExit(); 
  9     } 
 10  &nbsp;&nbsp; 
 11 &nbsp;    /**
 12 &nbsp;&nbsp; &nbsp; * 复制文件.
 13 &nbsp;&nbsp; &nbsp; * @param srcFileName
 14 &nbsp;&nbsp; &nbsp; * @param desFileName
 15 &nbsp;&nbsp; &nbsp; */
 16 &nbsp;&nbsp; &nbsp;public static void copyFile(String srcFileName, String desFileName) {
 17 &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;try {
 18 &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;FileChannel srcChannel = new FileInputStream(srcFileName)
 19 &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;.getChannel();
 20 
 21 &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;FileChannel dstChannel = new FileOutputStream(desFileName)
 22 &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;.getChannel();
 23 
 24 &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
 25 &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;
 26 &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;srcChannel.close();
 27 &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;dstChannel.close();
 28 &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;} catch (IOException e) {
 29 &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;e.printStackTrace();
 30 &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}
 31 &nbsp;&nbsp; &nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
 32 
 33         /**
 34      * 对指定文件添加字符串内容.
 35      * @param fileName
 36      * @param contant
 37      */
 38     public static void appendToFile(String fileName, String contant) {
 39         PrintWriter out;
 40         try {
 41             out = new PrintWriter(new BufferedWriter(new FileWriter(fileName,true)));
 42             out.print(contant);
 43             out.close();
 44         } catch (IOException e) {
 45             System.out.println("读写文件出现异常!");
 46         } catch (Exception e) {
 47             System.out.println("出现异常");
 48         }
 49     }
 50 
 51 &nbsp;&nbsp;&nbsp;&nbsp; /**
 52      * 读取文件为字节数组
 53      * @param filename
 54      * @return
 55      * @throws IOException
 56      */
 57     public static byte[] readFile(String filename) throws IOException {
 58         File file = new File(filename);
 59         if (filename == null || filename.equals("")) {
 60             throw new NullPointerException("无效的文件路径");
 61         }
 62         long len = file.length();
 63         byte[] bytes = new byte[(int) len];
 64         BufferedInputStream bufferedInputStream = new BufferedInputStream(
 65                 new FileInputStream(file));
 66         int r = bufferedInputStream.read(bytes);
 67         if (r != len)
 68             throw new IOException("读取文件不正确");
 69         bufferedInputStream.close();
 70         return bytes;
 71     }
 72 
 73     /**
 74      * 将字节数组写入文件 
 75      * @param data byte[]
 76      * @throws IOException
 77      */
 78     public static void writeFile(byte[] data, String filename)
 79             throws IOException {
 80         File file = new File(filename);
 81         BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
 82                 new FileOutputStream(file));
 83         bufferedOutputStream.write(data);
 84         bufferedOutputStream.close();
 85     }
 86 
 87     /**
 88      * 将字符数组转换为字节数组
 89      * @param chars
 90      * @return
 91      */
 92     public byte[] getBytes(char[] chars) {
 93         Charset cs = Charset.forName("UTF-8");
 94         CharBuffer cb = CharBuffer.allocate(chars.length);
 95         cb.put(chars);
 96         cb.flip();
 97         ByteBuffer bb = cs.encode(cb);
 98 
 99         return bb.array();
100     }
101 
102     /**
103      * 字节数组转换为字符数组
104      * @param bytes
105      * @return
106      */
107     public char[] getChars(byte[] bytes) {
108         Charset cs = Charset.forName("UTF-8");
109         ByteBuffer bb = ByteBuffer.allocate(bytes.length);
110         bb.put(bytes);
111         bb.flip();
112         CharBuffer cb = cs.decode(bb);
113         return cb.array();
114     }
115 
116     /**
117      * 读取指定文件的内容,返回文本字符串     
118      * @param fileName     文件名
119      * @param linkChar    换行符号
120      * @return
121      */
122     public static String readFile(String fileName, String linkChar) {
123         StringBuffer sb = new StringBuffer();
124         BufferedReader in;
125         String result = "";
126         try {
127             // 定义文件读的数据流
128             in = new BufferedReader(new FileReader(fileName));
129             String s;
130             while ((s = in.readLine()) != null) {
131                 sb.append(s);
132                 // 换行符号默认是13!!
133                 if (linkChar == null || "".equals(linkChar))
134                     sb.append((char) 13);
135                 else
136                     sb.append(linkChar);
137             }
138             in.close();
139             int i = linkChar.length();
140             result = sb.toString();
141             result = result.subSequence(0, sb.length() - i).toString();
142         } catch (FileNotFoundException e) {
143             System.out.println("找不到文件" + fileName + "!");
144             throw new Exception("文件找不到!");
145         } catch (IOException e) {
146             System.out.println("出现异常!");
147             throw new Exception("文件找不到!");
148         } catch (Exception e) {
149             e.printStackTrace();
150             System.out.println("出现异常!");
151             throw new Exception("文件找不到!");
152         } finally {
153             return result;
154         }
155     }
156 
157     /**
158      * 将指定文件中的内容已每行转换为字符串数组     
159      * @param fileName
160      * @return
161      */
162     public static String[] readFileToStrArr(String fileName) {
163         BufferedReader in;
164         ArrayList list = new ArrayList();
165         String[] result = null;
166         try {
167             // 定义文件读的数据流
168             in = new BufferedReader(new FileReader(fileName));
169             String s;
170             while ((s = in.readLine()) != null) {
171                 list.add(s);
172             }
173             result = new String[list.size()];
174             Iterator it = list.iterator();
175             int index = 0;
176             while (it.hasNext()) {
177                 result[index++] = it.next().toString();
178             }
179             return result;
180         } catch (FileNotFoundException e) {
181             System.out.println("找不到文件!");
182             throw new Exception("文件找不到!");
183         } catch (IOException e) {
184             System.out.println("出现异常!");
185             throw new Exception("文件找不到!");
186         } finally {
187             return result;
188         }
189     }
190 
191     /**
192      * 将字符串写进文件     
193      * @param fileName  文件名
194      * @param contant   要写入文件的字符串
195      */
196     public static void writeFile(String fileName, String contant) {
197         PrintWriter out;
198         try {
199             out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
200             out.print(contant);
201             out.close();
202         } catch (IOException e) {
203             System.out.println("读写文件出现异常!");
204         } catch (Exception e) {
205             System.out.println("出现异常");
206         }
207     }
208 
209     /**
210      * 字符串转换为字符数组
211      * @param str
212      * @return
213      */
214     public static char[] strToChars(String str) {
215         try {
216             byte[] temp;
217             temp = str.getBytes(System.getProperty("file.encoding"));
218             int len = temp.length;
219             char[] oldStrbyte = new char[len];
220             for (int i = 0; i < len; i++) {
221                 char hh = (char) temp[i];
222                 if (temp[i] < 0) {
223                     hh = (char) (temp[i] + 256);
224                 }
225                 oldStrbyte[i] = hh;
226             }
227             return oldStrbyte;
228         } catch (UnsupportedEncodingException e) {
229             e.printStackTrace();
230         }
231         return null;
232     }

下面是一些零散的知识点:::

得到控制台的输入字符串: 

 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流的默认设置.

 

转载请注明出处: http://renjie120.iteye.com/

posted @ 2013-11-26 20:54  黑夜骑士17  阅读(165)  评论(0编辑  收藏  举报