java读写txt、json、Excle

一、读写txt文本
java中IO流可以用来读写文本,分为字符流和字节流。这里以字符流为例。
1、读取:将txt中的文本存入List

public List<String> readTxt (String readFilePath) throws IOException {
    List<String> content = new ArraryList<String>();
    String line;
    BufferedReader br = new BufferedReader(new FileReader(ReadFilePath));
    while ((line = br.readline()) != null){   // 按行读取
	content.add(line);
    }
    br.close();
}

2、写入:将一个Map<String,Double>写入txt,键值之间以空格分割。

public void writeTxt (Map<String,Double> map, String writeFilePath) throws IOException {
    BufferedWriter bw = new BufferedWriter(new FileWriter(writeFilePath));
    Iterator<Map.Entry<String,Double>> it = map.entrySet().iterator();
    while (it.hasNext()){
	Map.Entry<String,Double> entry = it.next();
	bw.write(entry.getKey() + "\t" + entry.getValue());
    }
    bw.flush();
    bw.close();
}

二、读取json格式的txt文档:形如{“tag” : “类别名”, “word_tfidf” : [ {“word1” : tfidf1}, {“word2” : tfidf2 } ] }
这是需要的Maven:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.32</version>
</dependency>
public void readJsonTxt (String filePath) throws IOException {
    String line;
    BufferedReader br = new BufferedReader(new FileReader(filePath));
    while ((line = br.readerline()) != null){
	JSONObject object = JSON.parseObject(line);
	String str = object.getString("tag");   // str为:类别名
	JSONArray array = object.getJSONArray("word_tfidf");
	for(int i=0;i<array.size();i++){
	    JSONObject object2 = array.getJSONObject(i);
	    double value = object2.getDouble("word1");  
	    System.out.print(value + ", ");   // 输出: tfidf1, tfidf2
	}
    }
}

三、json文件读写,Maven如下:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

1、读取json内容,filePath路径中的数据格式如下,一行一个json:
[
{“title” : “***”, “content” : “-----”},
……
]

public Map<String,String> readJson (String filePath) throws IOException {
    Map<String, String> map = new HashMap<String,String>();
    String str = FileUtils.readFileToString(new File(filePath),"utf-8");
    JSONArray array = JSON.parseArray(str);
    for (int i=1; i<array.size(); i++){
    	JSONObject object = array.getJSONObject(i);
    	String title = object.getString("title");
    	String content = object.getString("content");
    	map.put(title,content);
    }
    return map;
}

2、内容写入.json

public void writeJson (String filePath) throws IOException {
    Map<String, Double> map = new HashMap<String,Double>;
    Map<String,Map<String,Double>> mapScore = new HashMap<String,Map<String,Double>>();
    map.put("诛仙", 4.9);
    map.put("凡人", 4.6);
    map.put("遮天", 4.5);
    mapScore.put("小说评分", map);
    
    File file = new File(filePath);
    FileUtils.write(file, "[\n", "utf-8", true);
    Iterator<Map<String,Map<String,Double>>> it = mapScore.entrySet().iterator();
    while (it.hasNext()){
        Map.Entry<String,Map<String,Double>> entry = it.next();
        Iterator<Map<String,Double>> it2 = entry.getValue.entrySet().iterator();
        while (it2.hasNext()){
            Map.Entry<String,Double> entry2 = it2.next();
            JSONObject object = new JSONObject();
            object.put("tag", entry.getKey());
            object.put("name", entry2.getKey());
            object.put("score", entry2.getValue());
            FileUtils.write(file, object.toJSONString, "utf-8", true);
            FileUtils.write(file, ",\n", "utf-8", true); 
        }
    }
    FileUtils.write(file, ""]\n, "utf-8", true);
}

四、读取Excel,Maven如下:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.16</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.14</version>
</dependency>
public List<List<String>> readxls(String xlsPath) throws IOException {
    List<List<String>> xlsContent = new ArrayList<List<String>>();
    FileInputStream fileIn = new FileInputStream(xlsPath);
    Workbook workbook;
    if (xlsPath.indexOf(".xlsx") > -1) {
        workbook = new XSSFWorkbook(fileIn);
    } else {
        workbook = new HSSFWorkbook(fileIn);
    }
    if (workbook != null) {
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {  // 遍历表单
            Sheet sheet = workbook.getSheetAt(i);
            for (Row row : sheet) {  // 遍历行
                List<String> rowData = new ArrayList<String>();
                if (row != null) {
                    for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
                        rowData.add(row.getCell(j).toString());
                    }
                }
                xlsContent.add(rowData);
            }
        }
    }
    fileIn.close();
    return xlsContent;
}

读取csv:

public List<String[]> readCsv (String filePath) throws IOException {
    List<String[]> csvList = new ArrayList<String[]>();
    CsvReader reader = new CsvReader(myFilePath,',',Charset.forName("GBK"));
    reader.readHeaders();
    while (reader.readRecord()){
       csvList.add(reader.getValues());
    }
    reader.close();
    return csvList;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值