获取本地目录里所有内容为xml格式的txt文件,并转成json对象

一、先获取项目中配置路径

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
//获取项目中properties文件配置

public final class GetProperties {
    private   static  String param;  
    private   static  String type; 
    static  {  
       Properties prop =  new  Properties();  
       InputStream in = Object. class .getResourceAsStream( "/application.properties" );  
        try  {  
           prop.load(in);  
           param = prop.getProperty( "xml.filepath" ).trim();  
           type = prop.getProperty( "xml.type" ).trim();  
       }  catch  (IOException e) {  
           e.printStackTrace();  
       }  
   }  
    /**  
    * 私有构造方法,不需要创建对象  
    */   
    private  GetProperties() {  
   }  

    public   static  String getParam() {  
        return  param;  
   }  
    public   static  String getType() {  
        return  type;  
   }  
   
}
 

 

 

二、

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
//工具类
public class ToJsonUtil {
    //获取目录下所有txt文件格式转json封装成对象
    public static List<Object> ToJson() throws IOException, JDOMException {
        List<Object> jsonObjects=new ArrayList<Object>();
        //获取properties文件配置路径
           String filePath =GetProperties.getParam();
           File file=new File(filePath);
           //获取文件过滤类型txt
           String extName =GetProperties.getType();
           //创建数据参数准备存储文件全路径
           List<String> listTxtname=new ArrayList<String>();
           //开始获取路径全部txt文件
           List<String> list=getfile(file,extName,listTxtname);
           //遍历路径
           for (String path : list) {
              System.out.println(path); 
              //读取txt文件内容
              String  xml= LoadContentByPath(path); 
              System.out.println("txt内容"+xml); 
  
                          JSONObject json=xml2JSON(xml.replace("UTF-8","utf-8").getBytes());

//封装成对象
                          JsonObject jsonList=new JsonObject();
                          jsonList.setPorttype(1);
                          jsonList.setJson(json);
                          jsonObjects.add(jsonList);
                          System.out.println(json.toJSONString());
                      
            }
               
          }
           
       
        return jsonObjects;
        
    }
    //判断字符串是否包含某个字符
    public static boolean isContain(String s1,String s2) {
           return s1.contains(s2);
    }
    /**
     * xml转换成json
     */
    public static JSONObject xml2JSON(byte[] xml) throws JDOMException, IOException {
        JSONObject json = new JSONObject();
        InputStream is = new ByteArrayInputStream(xml);
        SAXBuilder sb = new SAXBuilder();
        org.jdom2.Document doc = sb.build(is);
        Element root = doc.getRootElement();
        json.put(root.getName(), iterateElement(root));
        return json;
      }
    private static JSONObject iterateElement(Element element) {
        List node = element.getChildren();
        Element et = null;
        JSONObject obj = new JSONObject();
        List list = null;
        for (int i = 0; i < node.size(); i++) {
          list = new LinkedList();
          et = (Element) node.get(i);
          if (et.getTextTrim().equals("")) {
            if (et.getChildren().size() == 0)
              continue;
            if (obj.containsKey(et.getName())) {
              list = (List) obj.get(et.getName());
            }
            list.add(iterateElement(et));
            obj.put(et.getName(), list);
          } else {
            if (obj.containsKey(et.getName())) {
              list = (List) obj.get(et.getName());
            }
            list.add(et.getTextTrim());
            obj.put(et.getName(), list);
          }
        }
        return obj;
      }
      
      //读取txt文件内容
      public static String LoadContentByPath(String path) throws IOException {
          BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path),"gbk"));
          StringBuffer buffer = new StringBuffer();
          String line = "";
          while ((line = in.readLine()) != null){
              buffer.append(line);
          }
          return buffer.toString();

      }
     //获取,目录下所有txt文件列表
      public static List<String> getfile(File f,String extName,List<String> listTxtname){
        
       if(f==null)
       {
        return listTxtname;
       }
       if(f.isDirectory())
       {
        File tempfile[]=f.listFiles();
        if(tempfile!=null)
        {
         for (File file : tempfile) {
           getfile(file,extName, listTxtname)
         }
        }
       }else
       {
        String path=f.getPath().toLowerCase();
        if(path.endsWith(extName))
        {
            listTxtname.add(f.getPath());
        }
       }
       return listTxtname;
     
    }

}
 

三、封装返回对象

package xmlTest;

//liuxd  json返回封装对象
public class JsonObject {
    private int Porttype;
    private Object Json;
    public int getPorttype() {
        return Porttype;
    }
    public void setPorttype(int porttype) {
        Porttype = porttype;
    }
    public Object getJson() {
        return Json;
    }
    public void setJson(Object json) {
        Json = json;
    }
    @Override
    public String toString() {
        return "JsonObject [Porttype=" + Porttype + ", Json=" + Json + "]";
    }

}
四、main测试

import java.io.IOException;
import java.util.List;
import org.jdom2.JDOMException;
public class MainTest {

     public static void main(String[] args) throws JDOMException, IOException {
         List<Object> json=ToJsonUtil.ToJson();
         for (Object jsonObject : json) {
            System.out.println("####"+jsonObject.toString());
        }
     }
        

}
 

五、配置文件.properties内容

xml.filepath=C:/Users/GZLX/Desktop/xml
xml.type=.txt

Java中,你可以使用`java.io`和`org.json`库来读取本地JSON文件,并通过HTTP响应将其发送给浏览器。以下是简单的步骤: 1. **导入依赖**: 首先,你需要添加`json.org`的JSON处理库,可以引入Maven坐标: ```xml <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20210307</version> </dependency> ``` 2. **读取JSON文件**: 使用`BufferedReader`从硬盘读取文件内容,然后解析成JSONObject或JSONArray: ```java import org.json.JSONObject; try { File file = new File("path_to_your_file.json"); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuilder jsonContent = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { jsonContent.append(line); } reader.close(); JSONObject jsonObject = new JSONObject(jsonContent.toString()); } catch (IOException e) { e.printStackTrace(); } ``` 3. **创建HTTP响应**: 使用`javax.servlet.http.HttpServletResponse`发送数据到浏览器: ```java import javax.servlet.http.HttpServletResponse; HttpServletResponse response = ... // 获取HttpServletRequest的response对象 response.setContentType("application/json"); response.getWriter().write(jsonObject.toString()); ``` 4. **整合在Servlet或Spring MVC中**: 这些代码通常会在Web应用的控制器、Servlet或REST API中运行。 ```java @Controller public class JsonController { @GetMapping("/json") public void serveJson(HttpServletResponse response) { // 上述代码片段 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值