通过csv和json对数据进行读写操作

故事背景

需求,在首次软件烧录测试时,从usb设备中获取唯一的设备标识符UUID和Authkey,同时保存在设备中,类似同批设备的uuid是唯一的。
uuid是从第三方按批次采购的,以csv文件保存为例,做的处理,直白就是从csv读取第二行的id、保存为json、删除第二行id,保证不重复性。
数据操作比较小,所以删除读取过的数据,猜测,数据过多时,以特有的文件保存上一个设备烧录读取的行数据,读取后增1,会优化读写速度。

1. 读取csv指定行列(第2行,第1列)数据,然后删除指定csv指定行数据。

 String uuid = FileUtils.readDataFromCsv(dataFiles[0].getAbsolutePath(),2,1);
 FileUtils.deleteDataFromCsv(dataFiles[0].getAbsolutePath(),2);
	/**
     * 读取cvs指定行、列的数据
     * 
     * @param filePath
     * @param row
     * @param col
     * @return
     */
    public static String readDataFromCsv(String filePath, int row, int col) {
        boolean isExist = checkFileExist(filePath);
        String data = null;
        FileInputStream fileInputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        if (!isExist) {
            return null;
        } else {
            try {
                fileInputStream = new FileInputStream(new File(filePath));
                inputStreamReader = new InputStreamReader(fileInputStream);
                reader = new BufferedReader(inputStreamReader);
                String line = null;
                int index = 0;
                while ((line = reader.readLine()) != null) {
                    String item[] = line.split(",");// CSV格式文件为逗号分隔符文件,这里根据逗号切分
                    if (index == (row-1)) {
                        if (item.length >= col - 1) {
                            data = item[col - 1];
                            break;
                        }
                    }
                    index++;
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fileInputStream != null) {
                        fileInputStream.close();
                    }
                    if (inputStreamReader != null) {
                        inputStreamReader.close();
                    }
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return data;
            }
        }
    }
    /**
     * 删除cvs指定行的数据
     * 
     * @param filePath
     * @param row
     * @return
     */
    public static void deleteDataFromCsv(String filePath, int row) {
        boolean isExist = checkFileExist(filePath);
        String data = null;
        FileInputStream fileInputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        FileOutputStream fileOutputStream = null;
        PrintStream printStream = null;
        if (!isExist) {
            return ;
        } else {
            try {
                fileInputStream = new FileInputStream(new File(filePath));
                inputStreamReader = new InputStreamReader(fileInputStream);
                reader = new BufferedReader(inputStreamReader);
                StringBuffer sb = new StringBuffer("");
                String line;
                int index = 0;
                while ((line = reader.readLine()) != null) {
                    String item[] = line.split(",");// CSV格式文件为逗号分隔符文件,这里根据逗号切分
                    if (index != (row-1)) {
                        sb.append(line);
                        sb.append("\n");
                    }
                    index++;
                }
                fileOutputStream = new FileOutputStream(new File(filePath));
                printStream = new PrintStream(fileOutputStream);
                printStream.print(sb.toString());//重载方法,第二个参数true,表示在后面追加
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fileInputStream != null) {
                        fileInputStream.close();
                    }
                    if (inputStreamReader != null) {
                        inputStreamReader.close();
                    }
                    if (reader != null) {
                        reader.close();
                    }
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    if (printStream != null) {
                        printStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return ;
            }
        }
    }

2.新建json文件保存数据

/**
     * uuid保存
     * 写入/restore/product_config.json
     */
    private void writeUuidToFile(String uuid,String authkey) {
        String content = "{\"UUID\":\""+uuid+"\",\"AUTHKEY\":\""+authkey+"\"}";
        FileUtils.writeStringToFile(content,"/restore", "product_config.json");
    }

	//写入指定内容到指定文件
	public static void writeStringToFile(String json, String path, String fileName) {
        try {
            createFile(path, fileName);
            String utfJsonStr = new String(json.getBytes("UTF-8"), "UTF-8");
            FileOutputStream fileOutputStream = new FileOutputStream(new File(path, fileName));
            fileOutputStream.write(utfJsonStr.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static void createFile(String path, String fileName) throws IOException {
        File filePath = new File(path);
        File file = new File(path, fileName);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
    }

3.读取json文件数据

	private void getProductConfig() {
        if(!GetJsonDataUtil.isConfigExists()){
            return;
        }
        String json = GetJsonDataUtil.getJson();
        android.util.Log.d(TAG,"getProductConfig , json : " + json);
        try {
            org.json.JSONObject jsonObject = new org.json.JSONObject(json);
            config.setUuid(jsonObject.optString(GetJsonDataUtil.KEY_UUID));
            config.setAuthorKey(jsonObject.optString(GetJsonDataUtil.KEY_AUTHOR_KEY));
        } catch (JSONException e) {
            android.util.Log.d(TAG, e.toString());
            e.printStackTrace();
        }
    }

	public static final String PATH_CONFIG = "/restore/product_config.json";
	public static String getJson() {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            InputStream instream = new FileInputStream(PATH_CONFIG);
            BufferedReader bf = new BufferedReader(new InputStreamReader(instream));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

附加获取usb挂载文件的绝对路径

public static String getFilePath() {
	File path = new File(ROOT_DIR);
        File[] list = path.listFiles();
        if (list.length > 0) {
            for (File file : list) {
                File[] dataFiles = file.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                        String fileName = name.toLowerCase();
                        if (fileName.equals(UUID_FILE)) {
                            return true;
                        }
                        return false;
                    }
                });
            }
            if (dataFiles.length > 0) {
            	return dataFiles[0].getAbsolutePath();
            }
       }
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值