Java中同时读写字符和字节

1、 说明

最近,遇到在同一个文件中读写将文字信息(字符)和数据(字节)两种分开的数据。在Java中读写文件要么使用字符流仅仅读写字符,要么使用字节流仅仅读写字节,或者使用字节转换流,将字节流转换为字符流,再读写文件。但是不存在,能同时读写字符和字节的流。

2、 思路

针对,同时读写字符和字节可以换一种思路,第一种方法是先将字符转换为字节,然后以字节流的方式读写;第二种方法是先将字节转换为字符,然后以字符流的方式读写;第三种方法是同时使用字节流和字符流读写文件;第四种方法是将字符和字节分开为两个文件,一个是头文件、另一个是数据文件。

3、实例

本文使用的是第一种方法,先将文字信息(字符)转换为字节,然后使用字节流读写文件。文字信息与数据之间添加3个“0XFF”字节作为分隔符,区分文字信息和数据。

例如向文件中写入以下信息: 

  字符数据:“ 姓名:袁先生, 性别:男, 年龄:68, 增益:6 , 疾病:心电疾病 风湿性心脏病”

  字节数据:两个初始化都是0的byte[25],设置第一个byte[25]中byte[0]=99,第二个byte[25]中byte[0]=98

最终文件中的数据是: {'name':'袁先生','sex':'男','age':68,'gain':6,'disease':['心电疾病','风湿性心脏病']}" 0XFF 0XFF 0XFF 1100011 00000000 …… 00000000  1100010  00000000 …… 00000000;

由于我写入的文件的数据字符数据比较少,而字节数据比较多,所以,我采用了先将字符转化为字节,然后,使用字节流写入到文件中,并且仪3个“0XFF”作为分隔符。

代码如下:

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.ArrayList;

 

public class Test {

       public static void main(String[] args) {

              Test test = new Test();

             

              // Write the file

              test.writeFile();

              // Read the file

              test.readFile();

       }

      

       public boolean writeFile() {

              File dirDat= new File("yong");             

              // The directory is exists

              if(!dirDat.exists()) {

                     if(!dirDat.mkdirs()) {

                            return false;

                     }

              }             

              String fileName= "yuan.dat";

              File saveFile = new File(dirDat, fileName);     

             

              String inforUserStr = "{'name':'袁先生','sex':'男','age':68,'gain':6,'disease':['心电疾病','风湿性心脏病']}";

              byte[] inforUserByte = inforUserStr.getBytes();

             

              //Output the data

              try {

                     FileOutputStream fosDat = new FileOutputStream(saveFile);

                    

                     // Write the information of user

                     fosDat.write(inforUserByte);

                    

                     // Write split identifier flag

                     byte[] flag = new byte[] {(byte) 0XFF,(byte) 0XFF,(byte) 0XFF};

                     fosDat.write(flag);             

                     // Write the data

                     byte[] data = new byte[25];

                     data[0] = 99;

                     fosDat.write(data);

                     data[0] = 98;

                     fosDat.write(data);                   

                     fosDat.close();

                    

                     // Set the file is read only

//                   saveFile.setReadOnly();

                    

               } catch (FileNotFoundException e) {

                      System.out.println("WriteDat, New FileOutputStream error !");

                      e.printStackTrace();

            } catch (IOException e) {

                  System.out.println("WriteDat, Close the FileOutputStream error !");

                  e.printStackTrace();

           }         

              return true;

       }

      

       public boolean readFile() {

              File dirDat= new File("yong");          

              // The directory is exists

              if(!dirDat.exists()) {

                     return false;

              }           

              String fileName= "yuan.txt";

              File saveFile = new File(dirDat, fileName);

              ArrayList<Byte> inforUserByteList = new ArrayList<Byte>();

              // The byte[25] is one point data

              byte[] pointData = new byte[25];

              // Read the data        

              try {

                     FileInputStream fisDat = new FileInputStream(saveFile);

                     boolean readFlag = true;

                     byte splitFlag = 0;

                     while(readFlag) {

                            // Get the user information

                            if(splitFlag < 3) {                                 

                                   // The byte use to find the split identifier flag

                                   byte inforUserByte = (byte) fisDat.read();

                                   // Add the information into the list

                                   inforUserByteList.add(inforUserByte);

                                   // Judge the split identifier flag

                                   if(inforUserByte == (byte)0XFF) {

                                          splitFlag = (byte) (splitFlag + 1);

                                   }else {

                                          splitFlag = 0;

                                   }

                            // Get the data

                            }else {

                                   if(fisDat.read(pointData) > 0) {

                                          System.out.println("数据:"+pointData[0]);

                                   }else {

                                          readFlag = false;

                                   }

                            }

                     }

              } catch (FileNotFoundException e) {

                     System.out.println("ReadDat, Establish the FileInputStream error !");

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              } catch (IOException e) {

                     System.out.println("ReadDat, Read the FileInputStream error !");

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }         

              byte[] inforUserByte = (byte[]) new byte[inforUserByteList.size()];

              // Remove the flag, and transform the string

              for(int i=0; i<inforUserByteList.size()-3; i++){

                     inforUserByte[i] = inforUserByteList.get(i);

              }

              String inforUserStr = new String(inforUserByte);

              System.out.println(inforUserStr);

              return false;

       }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值