Java字节与字符流永久存储json数据

时间:2022-09-18 15:18:34

使用第三方json转换工具,阿里巴巴json转换工具Fastjson1.2.7。

注意:jar包的导入不再赘述,详见百度。

User类,定义两种属性,并创建构造方法与get和set方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class User {
    public String userName; //名字
    public double balance; //金额
    public User() {
        super();
    }
    public User(String userName, double balance) {
        super();
        this.userName = userName;
        this.balance = balance;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public double getBalance() {
        return balance;
    }
    public void setBalance(double balance) {
        this.balance = balance;
    }
}

字节流的方式存储json数据到txt文件

?
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
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
 
import java.util.ArrayList;
import java.util.List;
 
import com.alibaba.fastjson.JSON;
 
public class ListFile {
    public static void main(String[] args){
        List<User> list=new ArrayList<>();
        list.add(new User("张三",100));
        list.add(new User("张四",200));
        list.add(new User("张五",300));
        File file=new File("D:/uselist.txt"); //存储的目标文件
        FileOutputStream fos=null;
        BufferedOutputStream bos=null;
        try{
            fos=new FileOutputStream(file);
            bos=new BufferedOutputStream(fos);
            String json=JSON.toJSONString(list); //对象转换为json
            bos.write(json.getBytes("utf-8")); //json字符串写入文件
            bos.flush();
            System.out.println("json数据写入完成");
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            try{
                fos.close();
                bos.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
        
        //读取文件内容,并在控制台输出
        String str="";
        int num=0;
        FileInputStream fis=null;
        BufferedInputStream bis=null;
        byte buff[]=new byte[1024];
        try{
            fis=new FileInputStream(file);
            bis=new BufferedInputStream(fis);
            while((num=bis.read(buff))!=-1){
                str+=new String(buff,"utf-8");
            }
            System.out.println(str); //打印读取文件的json字符串
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            try{
                fis.close();
                bis.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
        
        //把读取到的json数据再转为对象,并在控制台输出
        list=JSON.parseArray(str.trim(),User.class); //读取到的json数据存在空格,trim方法去除
        for(User obj:list){
            System.out.println(obj.getUserName()+"\t"+obj.getBalance());
        }
    }
}

字符流的方式存储json数据到txt文件

?
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
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
 
import com.alibaba.fastjson.JSON;
 
public class ListFile {
    public static void main(String[] args){
        List<User> list=new ArrayList<>();
        list.add(new User("张三",100));
        list.add(new User("张四",200));
        list.add(new User("张五",300));
        File file=new File("D:/uselist.txt"); //存储的目标文件
        FileWriter fw=null;
        BufferedWriter bw=null;
        
        try{
            fw=new FileWriter(file);
            bw=new BufferedWriter(fw);
            String json=JSON.toJSONString(list); //对象转换为json
            bw.write(json); //json字符串写入文件
            bw.flush();
            System.out.println("json数据写入完成");
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            try{
                bw.close();
                fw.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
        
        //读取文件内容,并在控制台输出
        String str="";
        String s="";
        FileReader fr=null;
        BufferedReader br=null;
        try{
            fr=new FileReader(file);
            br=new BufferedReader(fr);
            while((s=br.readLine())!=null){
                str+=s;
            }
            System.out.println(str); //打印读取文件的json字符串
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            try{
                br.close();
                fr.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
        
        //把读取到的json数据再转为对象,并在控制台输出
        list=JSON.parseArray(str.trim(),User.class);
        for(User obj:list){
            System.out.println(obj.getUserName()+"\t"+obj.getBalance());
        }
    }
}

运行结果:

?
1
2
3
4
5
json数据写入完成
[{"balance":100,"userName":"张三"},{"balance":200,"userName":"张四"},{"balance":300,"userName":"张五"}]
张三  100.0
张四  200.0
张五  300.0

问题:为什么需要把对象转为json再存储?为什么不直接把对象存储到文件中?使用json有什么好处?

一二问回答:如果直接把对象写入文件中,会产生乱码,需要转换json字符串再存储。

三问回答:json的优点,方便于传输,较少冗余的字符,易于转换、阅读。

原文链接:https://www.idaobin.com/archives/894.html