java类:读文件类, 读取、创建xml文件, 填充jsp文件,数据转换为json类型
2010-08-24 21:42
1066 查看
读文件类:
读xml文件,创建xml文件:
读取配置文件中的内容填充进jsp文件中:
将数据转换为json类型:
configfile中的数据:
toer;;;192.168.97.60-192.168.97.200
ttt;;;192.168.97.60-192.168.97.200
xg;;;192.168.97.60-192.168.97.200
aaa;;;192.168.97.60-192.168.97.200
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ReadFile { // private String fileName = "/configFile/configfile"; public List readConfigFile(String fileName) { List list = new ArrayList(); String str; try { BufferedReader br = new BufferedReader(new FileReader(fileName)); while (br.ready()) { str = br.readLine(); String s[] = str.split(";;;"); for (int j = 0; j < s.length; j++) { list.add(s[j]); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } public static void main(String arg[]) { ReadFile rf = new ReadFile(); List list = rf .readConfigFile("F://workspace7.0//ajax//WebRoot//configFile//configfile"); System.out.println(list); } }
读xml文件,创建xml文件:
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.jboss.logging.Logger; public class ReadXmlFile { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ReadXmlFile rxf = new ReadXmlFile(); rxf.readXmlFile(new File( "F://workspace7.0//ajax//WebRoot//configFile//a.xml")); // rxf.createXmlFile(new // File("F:/workspace7.0/ajax/WebRoot/configFile/a.xml")); } /**读取XML文件 * @param xmlFile */ public void readXmlFile(File xmlFile) { SAXReader read = new SAXReader(); Logger log = Logger.getLogger(this.getClass()); String s = null; try { Document d = read.read(xmlFile); Element root = d.getRootElement(); for (Iterator i = root.elementIterator(); i.hasNext();) { Element element = (Element) i.next(); System.out.println(element.toString()); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 创建xml文件 * * @param file */ public void createXmlFile(File file) { Document document = DocumentHelper.createDocument(); Element root = document.addElement("book"); Element nameElement = root.addElement("name"); nameElement.addAttribute("title", "xxxbook"); nameElement.addText("java develop开发"); // document.addDocType("catalog", null,"file://c:/Dtds/catalog.dtd"); try { /** 格式化输出*/ OutputFormat format = OutputFormat.createPrettyPrint(); /** 指定 XML编码 */ format.setEncoding("GBK"); XMLWriter writer = new XMLWriter(new FileWriter(file), format); writer.write(document); writer.close();// 必须关闭,不然输出文件中无内容 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
读取配置文件中的内容填充进jsp文件中:
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import org.jboss.logging.Logger; public class RewriteJSPFile { Logger log = Logger.getLogger(this.getClass()); /**将List中数据填充到filePath所对应的文件中 * @param list 存储数据的List * @param filePath 文件路径 */ public void rewriteJSP(List list, String filePath) { String html_start = "<html>"; String html_end = "</html>"; String body_start = "<body>"; String body_end = "</body>"; String a_start = "<a href=""; String a_end = "" mce_href=""; String a_end = "" ></a>"; String text_start = "<input type='text' value='"; String text_end = "' />"; StringBuffer sb = new StringBuffer(); sb.append(html_start).append(body_start).append(text_start).append( list.get(0).toString()).append(text_end).append(body_end).append(html_end); try { // String // s=ServletActionContext.getServletContext().getRealPath(filePath); // String file= // "F://workspace7.0//ajax//WebRoot//configFile//configfile//rewritejsp.html" // ; File f = new File(filePath); if (!f.exists()) { f.createNewFile(); } FileWriter fw = new FileWriter(f); fw.write(sb.toString()); log.info("已将配置文件数据填充到jsp页面中"); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 使用DOS的cmd命令拷贝文件 * * @param oldPath * @param newPath */ public void copyFileByDosCommand(String oldPath, String newPath) { String command = "cmd /c copy " + oldPath + " " + newPath;// 拷贝后关闭命令窗口 try { File oldFile = new File(oldPath); if (!oldFile.exists()) { log.error("cmd复制文件时,源文件不存在"); } Process pro = Runtime.getRuntime().exec(command); pro.waitFor(); log.info("执行cmd copy命令,复制文件"); if (pro.exitValue() != 0) { log.error("FileOperation.copyFileByCommand() 执行命令不正确!"); throw new Exception("复制文件命令出错"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { RewriteJSPFile r = new RewriteJSPFile(); r.copyFileByDosCommand("c://Data.dat", "c://copydata.txt"); ReadFile rf = new ReadFile(); List list = rf .readConfigFile("F://workspace7.0//ajax//WebRoot//configFile//configfile");//读取配置文件中的数据 r.rewriteJSP(list,"F://workspace7.0//ajax//WebRoot//configFile//rewritejsp.jsp");//将配置文件中数据填充到jsp文件中 } }
将数据转换为json类型:
package util; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.json.JSONObject; import com.googlecode.jsonplugin.JSONUtil; import com.sun.java_cup.internal.internal_error; import po.Student; import dao.IStudentDAO; /**将数据转换为json类型 * @author tower * */ public class ToJsonType { /** * 将list类型转变为json类型 <br> * {"rows":[{"id":0,"cell":[0,"11","11"]},{"id":1,"cell":[1,"22","22"]}]} * * @param studentList * @param map * @return */ public String ListToJsonString(List studentList) { List mapList = new ArrayList(); Map map=new LinkedHashMap(); for (int i = 0; i < studentList.size(); i++) { Student s = (Student) studentList.get(i); Map cellMap = new LinkedHashMap(); cellMap.put("id", s.getId()); cellMap.put("cell", new Object[] { s.getId(), s.getFirstname(), s.getLastname() }); mapList.add(cellMap); } map.put("page", 2); map.put("total",10);//总记录数 map.put("rows", mapList); JSONObject jsonObject = new JSONObject(map); return jsonObject.toString(); // List mapList=new ArrayList(); // StringBuffer sb=new StringBuffer(); // int j=studentList.size(); // sb.append("{"); // sb.append("'rows':["); // for (int i = 0; i < j; i++) { // Student student=(Student) studentList.get(i); // // sb.append("{'id':"+student.getId()+","); // sb.append("'cell':["+student.getId()+",'"+student.getFirstname()+"','"+student.getLastname()+"'"); // sb.append("]}"); // if(i!=(j-1)) // sb.append(","); // // } // sb.append("]"); // sb.append("}"); // String jsonString=sb.toString(); // return jsonString; } public static String object2json(Object obj) { StringBuilder json = new StringBuilder(); if (obj == null) { json.append("/"/""); } else if (obj instanceof String || obj instanceof Integer || obj instanceof Float || obj instanceof Boolean || obj instanceof Short || obj instanceof Double || obj instanceof Long || obj instanceof BigDecimal || obj instanceof BigInteger || obj instanceof Byte) { json.append("/"").append(string2json(obj.toString())).append("/""); } else if (obj instanceof Object[]) { json.append(array2json((Object[]) obj)); } else if (obj instanceof List) { json.append(list2json((List<?>) obj)); } else if (obj instanceof Map) { json.append(map2json((Map<?, ?>) obj)); } else if (obj instanceof Set) { json.append(set2json((Set<?>) obj)); } else { json.append(bean2json(obj)); } return json.toString(); } public static String bean2json(Object bean) { StringBuilder json = new StringBuilder(); json.append("{"); PropertyDescriptor[] props = null; try { props = Introspector.getBeanInfo(bean.getClass(), Object.class) .getPropertyDescriptors(); } catch (IntrospectionException e) { } if (props != null) { for (int i = 0; i < props.length; i++) { try { String name = object2json(props[i].getName()); String value = object2json(props[i].getReadMethod().invoke( bean)); json.append(name); json.append(":"); json.append(value); json.append(","); } catch (Exception e) { } } json.setCharAt(json.length() - 1, '}'); } else { json.append("}"); } return json.toString(); } public static String list2json(List<?> list) { StringBuilder json = new StringBuilder(); json.append("{ rows:["); if (list != null && list.size() > 0) { for (Object obj : list) { json.append(object2json(obj)); json.append(","); } json.setCharAt(json.length() - 1, ']'); json.append("}"); } else { json.append("]"); } return json.toString(); } public static String array2json(Object[] array) { StringBuilder json = new StringBuilder(); json.append("["); if (array != null && array.length > 0) { for (Object obj : array) { json.append(object2json(obj)); json.append(","); } json.setCharAt(json.length() - 1, ']'); } else { json.append("]"); } return json.toString(); } public static String map2json(Map<?, ?> map) { StringBuilder json = new StringBuilder(); json.append("{"); if (map != null && map.size() > 0) { for (Object key : map.keySet()) { json.append(object2json(key)); json.append(":"); json.append(object2json(map.get(key))); json.append(","); } json.setCharAt(json.length() - 1, '}'); } else { json.append("}"); } return json.toString(); } public static String set2json(Set<?> set) { StringBuilder json = new StringBuilder(); json.append("["); if (set != null && set.size() > 0) { for (Object obj : set) { json.append(object2json(obj)); json.append(","); } json.setCharAt(json.length() - 1, ']'); } else { json.append("]"); } return json.toString(); } public static String string2json(String s) { if (s == null) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); switch (ch) { case '"': sb.append("///""); break; case '//': sb.append("////"); break; case '/b': sb.append("//b"); break; case '/f': sb.append("//f"); break; case '/n': sb.append("//n"); break; case '/r': sb.append("//r"); break; case '/t': sb.append("//t"); break; case '/': sb.append("///"); break; default: if (ch >= '/u0000' && ch <= '/u001F') { String ss = Integer.toHexString(ch); sb.append("//u"); for (int k = 0; k < 4 - ss.length(); k++) { sb.append('0'); } sb.append(ss.toUpperCase()); } else { sb.append(ch); } } } return sb.toString(); } public static void main(String[] args) { ToJsonType jsonStudentBO2 = new ToJsonType(); Student student1 = new Student(); student1.setId(0); student1.setFirstname("11"); student1.setLastname("11"); Student student2 = new Student(); student2.setId(1); student2.setFirstname("22"); student2.setLastname("22"); List list = new ArrayList(); list.add(student1); list.add(student2); // String string = jsonStudentBO2.ListToJsonString(list, new LinkedHashMap()); String string = jsonStudentBO2.ListToJsonString(list); System.out.println(list); System.out.println(string); } }
configfile中的数据:
toer;;;192.168.97.60-192.168.97.200
ttt;;;192.168.97.60-192.168.97.200
xg;;;192.168.97.60-192.168.97.200
aaa;;;192.168.97.60-192.168.97.200
相关文章推荐
- SQL C# nvarchar类型转换为int类型 多表查询的问题,查询结果到新表,TXT数据读取到控件和数据库,生成在控件中的数据如何存到TXT文件中
- JAVA中数据的读取与写入,不同类型数据的转换
- 读取网址中json数据 转换为java格式
- JAVA基础 day23 IO流的其他类 (对象的序列化 管道流 RandomAccessFile类(随机读取文件) DateStream(操作基本数据类型的流) 操作数组的流 )字符编码问题
- oracle 时间类型 与java mybatis.xml 文件配置 resultMap 对应时间类型 JsonConfig 转换oracle里的时间类型
- 【GDAL/OGR】利用GDAL/OGR读取shp文件并转换为json文件(Java版)
- java字节分割转换 数据类型转换 文件输入流
- python json及mysql——读取json文件存sql、数据库日期类型转换、终端操纵mysql及python codecs读取大文件问题
- 使用java 程序创建格式为utf-8文件的方法(写入和读取json文件)
- Java将其他数据类型转换成JSON字符串格式
- 【JAVA】apache poi excel 文件读取,各种数据类型,不规则excel格式都可以读取
- JSON类型数据转换为对象,并排除指定的属性.JAVA将购物车数据写入到cookie中
- python json及mysql——读取json文件存sql、数据库日期类型转换、终端操纵mysql及python codecs读取大文件问题
- 序列化对象到Xml文件以及反序列话Xml文件到对象(序列化数据到8个Java原型类型)
- java其他类型数据转换为Json数据
- Java读取json文件并对json数据进行读取、添加、删除与修改操作
- 浅析Java中对象的创建与对象的数据类型转换
- java读取url中json文件中的json数据
- 读取xml文件转换为json文件
- java小程序从数据库中(表)中读取数据然后创建文件夹生成txt文件