首页 > 解决方案 > 如何在android中读取两种不同的字符串格式

问题描述

我正在从输入流中读取数据,其中字符串有两种不同的格式。

一种是带有以下标题的标题:

   Scale id,Rec.No,Date,Time,Bill No.,Item No.,Plu,Name,Qty,Rate,Amount,Void
    0,142,17/01/21,17:50,053,3848,001,POTATO          ,0.615,50.00,30.75,N
    0,143,17/01/21,17:50,053,3849,002,POTATO P        ,0.985,36.00,35.46,N
     0,144,17/01/21,17:50,053,3850,003,ONION P         ,1.550,15.00,23.25,N
    

第二种格式没有标题:

001,1234560,POTATO          ,0,000,K,50.00,15.258,@ 
002,1234561,POTATO P        ,0,000,K,36.00,15.258,@,0.00
003,1234562,ONION P         ,0,000,K,15.00,15.258,@,0.00
004,1234563,BR. CHU.CHU.    ,0,000,K,28.00,15.258,@,0.00
005,1234564,BR. ROUND       ,0,000,K,24.00,15.258,@,0.00

我想用两种不同的方法解析这两种不同的格式。

逻辑和我使用的逻辑:

 public void getReportResponse()throws IOException {
            BufferedReader br = null;
            str = new StringBuffer();
            int bytes = 0;
            byte[] packetBytes = new byte[256];
            try {
                br = new BufferedReader(new InputStreamReader(mmInStream));
                String line="";

                while ((line = br.readLine()) != null) {
                   // line = line.trim();
                    //dataparse.Data(s);
                    Log.i("DATA in getReportResponse", line);
                    if (line.matches("Scale id,Rec.No,Date,Time,Bill No.,Item No.,Plu,Name,Qty,Rate,Amount,Void")) {
                        do {
                            bytes = mmInStream.read( packetBytes );//READING THE INPUT STREAM
                            line = new String( packetBytes, 0, bytes );
                            // append the string in string buffer
                            str.append( line );
                            Log.i( TAG,"Report"+str);
                           // dataparse.ReportData(str.toString());
                            line="";
                        } while (str.length()!=-1);
                        Log.i( TAG,"REPORT"+str);
                        dataparse.ReportData(str.toString());//this method is for parse value without header after condition

                    } else {
                        String data = line.trim();
                        dataparse.Data(data);//this is working  yes//this one is for passing data without header

                        //  Log.i("DATA",line);
                    }
                }



            } catch (IOException e) {
                e.printStackTrace();

            }
        }

但是“如果”条件不起作用请帮助我

标签: javaandroid

解决方案


我只会检查一次标题,也只检查第一个标题元素

//... removed for brevity
br = new BufferedReader(new InputStreamReader(mmInStream));
String line = br.readLine();
if (line != null && line.startsWith("Scale id")) {
  handleHeader(line);
  line = br.readLine();
} 
while (line != null) {
    String data = line.trim();
    dataparse.Data(data);
    line = br.readLine();            
}
//... removed for brevity

请注意,用于if条件的所有代码都已移至handleHeader


推荐阅读