服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java读取文件内容,解析Json格式数据方式

java读取文件内容,解析Json格式数据方式

2021-12-21 13:39W-大泡泡 Java教程

这篇文章主要介绍了java读取文件内容,解析Json格式数据方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

java读取文件内容,解析Json格式数据

一、读取txt文件内容(Json格式数据)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static String reader(String filePath) {
    try {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = bufferedReader.readLine();
            while (lineTxt != null) {
                return lineTxt;
            }
        }
    } catch (UnsupportedEncodingException | FileNotFoundException e) {
        System.out.println("Cannot find the file specified!");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("Error reading file content!");
        e.printStackTrace();
    }
    return null;
}

二、解析处理Json格式数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private static void process(String txtStr) {
    JSONObject json = JSONObject.fromObject(txtStr);
    JSONArray datas = json.getJSONObject("data").getJSONArray("rows");
    List<Map<String, Object>> list = new ArrayList<>();
    for (int i = 0; i < datas.length(); i++) {
        Map<String, Object> map = new HashMap<>();
        JSONObject obj = datas.getJSONObject(i).getJSONObject("cells");
        String name = obj.getString("weibo_name");
        String code = obj.getString("weibo_id");
        String url = BASE_URL + obj.getString("url");
        map.put("name", name);
        map.put("code", code);
        map.put("url", url);
        list.add(map);
    }
    if (!list.isEmpty()) {
        insert(list);
    }
}

三、结果存入数据库

?
1
2
3
4
5
private static void insert(List<Map<String, Object>> list) {
    for (Map<String, Object> map : list) {
        //遍历数据,写存储方法
    }
}

四、测试

?
1
2
3
4
5
6
7
8
9
10
public static void main(String[] args) {
    String filePath = "E:\\wugang\\data\\weiboyi\\wechat.txt";
    String txtStr = reader(filePath);
    if (txtStr != null) {
        process(txtStr);
    } else {
        System.out.println("Read the content is empty!");
    }
    System.out.println("--- end ---");
}

java 读取txt文件中的json数据,进行导出

txt文件中的内容如下

以下代码可直接运行

java读取文件内容,解析Json格式数据方式

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package com.hwt.count.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import net.sf.json.JSONObject;
public class Testaa {
    public static void main(String[] args) {
        try {
            String path = "C:/Users/dell/Desktop/test.txt";
            File file = new File(path);
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file),"GBK");
            BufferedReader br = new BufferedReader(isr);
            String content = br.readLine() ;
            br.close();
            isr.close();
            content = content.substring(2, content.length()-2);
            content = content.replace("},{", ";");
            String[] arrContent = content.split(";");
            
            //设置列头名称和表体数据
            String[] rowsName = new String[]{"code_type","code","name"};
            List<Object[]> dataList = new ArrayList<Object[]>();
            
            for(String arrc : arrContent){
                JSONObject jsonObj = JSONObject.fromObject("{"+arrc+"}");
                String code = jsonObj.getString("code");
                String name = jsonObj.getString("name");
                Object[] obj = new Object[rowsName.length];
                obj[0] = "TYPE";
                obj[1] = code;
                obj[2] = name;
                dataList.add(obj);
            }
            //设置列头名称和表体数据
            HSSFWorkbook workbook = setWorkBookDate(dataList,rowsName);
            try {
                // 将workbook对象输出到文件test.xls
                FileOutputStream fos = new FileOutputStream("C:/Users/dell/Desktop/test.xls");
                workbook.write(fos);
                fos.flush(); // 缓冲
                fos.close(); // 关闭流
            }catch (Exception e1) {
                e1.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static HSSFWorkbook setWorkBookDate(List<Object[]>  dataList,String[] rowsName){
        
        //创建工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建工作表,设置当前页名称
        HSSFSheet sheet = workbook.createSheet("测试");
        //设置默认行高
        sheet.setDefaultRowHeight((short)350);
        //合并表头表尾的单元格
        /*sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 3));
        sheet.addMergedRegion(new CellRangeAddress(3, 3, 0, 3));
        //冻结行
        workbook.getSheetAt(0).createFreezePane(0, 4);
        RegionUtil.setBorderBottom(1, new CellRangeAddress(3, 3, 0, 3), workbook.getSheetAt(0), workbook);//设置边框
*/        // 获取表头样式对象
        // 获取表体样式对象
        HSSFCellStyle style = getCommonStyle(workbook);
        
        // 定义所需列数
        int columnNum = rowsName.length;
        //创建列头
        HSSFRow rowHead = sheet.createRow(0); 
        for(int n = 0;n < columnNum;n++){
            HSSFCell cellRow = rowHead.createCell(n,HSSFCell.CELL_TYPE_STRING);//创建列头对应个数的单元格               
            cellRow.setCellValue(rowsName[n]);//设置列头单元格的值                       
            cellRow.setCellStyle(style);//设置列头单元格样式                       
        }
        
        //将查询出的数据设置到sheet对应的单元格中
        for(int i=0;i<dataList.size();i++){
            Object[] obj =new Object[dataList.get(i).length];
            obj[0] = dataList.get(i)[0];
            obj[1] = dataList.get(i)[1];
            obj[2] = dataList.get(i)[2];
            HSSFRow row = sheet.createRow(i+1);//创建所需的行数
            for(int j = 0; j < obj.length; j++){
                HSSFCell cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);//设置单元格的数据类型  
                if(!"".equals(obj[j]) && obj[j] != null){
                    cell.setCellValue(obj[j].toString());//设置单元格的值                       
                }else{
                    cell.setCellValue("");//设置单元格的值为空字符串
                }
                cell.setCellStyle(style);//设置单元格样式                                   
            }
        }
        //让列宽随着导出的列长自动适应
        for (int colNum = 0; colNum < columnNum; colNum++) {
            int columnWidth = sheet.getColumnWidth(colNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                //当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
                if (currentRow.getCell(colNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(colNum);
                    if(currentCell != null && !"".equals(currentCell)){
                        if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                            int length = currentCell.getStringCellValue().getBytes().length;
                            if (columnWidth < length) {
                                columnWidth = length;
                            }
                        }
                    }
                }
            }
            if(colNum == 0){
                //设置表体第一列的宽度
                sheet.setColumnWidth(colNum, (columnWidth+4) * 400);
            }else{
                //设置表体其他列的宽度
                sheet.setColumnWidth(colNum, (columnWidth+4) * 400);
            }
        }
        return workbook;
    }
    public static HSSFCellStyle getCommonStyle(HSSFWorkbook workbook) {
      // 设置字体
      HSSFFont font = workbook.createFont();
      //设置字体大小
      font.setFontHeightInPoints((short)11);
      //字体加粗
      //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
      //设置字体名字
      font.setFontName("Courier New");
      //设置样式;
      HSSFCellStyle style = workbook.createCellStyle();
      //设置底边框;
      style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
      //设置底边框颜色; 
      style.setBottomBorderColor(HSSFColor.BLACK.index);
      //设置左边框;  
      style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
      //设置左边框颜色;
      style.setLeftBorderColor(HSSFColor.BLACK.index);
      //设置右边框;
      style.setBorderRight(HSSFCellStyle.BORDER_THIN);
      //设置右边框颜色;
      style.setRightBorderColor(HSSFColor.BLACK.index);
      //设置顶边框;
      style.setBorderTop(HSSFCellStyle.BORDER_THIN);
      //设置顶边框颜色; 
      style.setTopBorderColor(HSSFColor.BLACK.index);
      //在样式用应用设置的字体; 
      style.setFont(font);
      //设置自动换行;
      style.setWrapText(false);
      //设置水平对齐的样式为居中对齐; 
      style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
      //设置垂直对齐的样式为居中对齐;
      style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
      return style;
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u011389474/article/details/52700443

延伸 · 阅读

精彩推荐