年轻人,你对io一无所知

最近遇到了一个关于io的问题。一个4G的文件需要我读出来,然后处理下放到数据库里。4G,拿到的时候只是觉得大了点。怕啥,读出来,处理好,ok。保存。。。。。。

那么,开干吧。

@RequestMapping("xxxx")
   @ResponseBody
   @Transactional(readOnly = false,propagation = Propagation.REQUIRED)
   public  String readText(HttpServletRequest request,String type){
      File file = new File("xxxx.json");
      StringBuilder result = new StringBuilder();
      try{
         BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
         String s = null;
         while((s = br.readLine())!=null){//使用readLine方法,一次读一行
            JSONObject json = JSONObject.parseObject(s);
            //处理业务
         }
         br.close();
      }catch(Exception e){
         e.printStackTrace();
      }
      return result.toString();
   }
明显,失败咧。根本读不出来。太大了,赶紧找外援。然后老大说要用流来处理(嘛是流),并且你要想办法把数据切割下。。。。。巨尴尬。好吧,滚滚爬爬,还是借鉴来了老大的代码。脸为何物?对于这个问题吗,不会就借鉴,借鉴了就要及时总结。

@RequestMapping("/xxxx")
@ResponseBody
public String uploadAreaPersonLocal(HttpServletRequest request, String fileName, String type) throws JSONErrorException {
   Map<String,Object> map = new HashMap<>();
   Reader reader = null;
   int count = 0;
   try {
      StringBuilder builder = new StringBuilder();
      int charread = 0;
      JSONArray array = new JSONArray();
      reader = new InputStreamReader(new FileInputStream(fileName));
      // 读入多个字符到字符数组中,charread为一次读取字符数
      while ((charread = reader.read()) != -1) {
         if ((char)charread == '[') {
            break;
         }
      }
      while ((charread = reader.read()) != -1) {
         char tempChar = (char)charread;
         if (tempChar == ']') {
            break;
         }
         if (tempChar == '{') {
            builder.setLength(0);
         }
         builder.append(tempChar);
         if (tempChar == '}') {
            array.add(JSON.parseObject(builder.toString()));
            builder.setLength(0);
         }
         if (array.size() >= 10000) {
            array = new JSONArray();
            count = count + 10000;
         }
      }
      if (array.size() > 0) {
         if (Integer.valueOf(type) == 1) {
            this.cityDataService.saveLivePeople(array);
         } else if(Integer.valueOf(type) == 2) {
            this.cityDataService.saveDailyPeople(array);
         }
         System.out.println("已保存:" + (count + array.size()));
      }
   } catch (Exception e1) {
      e1.printStackTrace();
   } finally {
      if (reader != null) {
         try {
            reader.close();
         } catch (IOException e1) {
         }
      }
   }
   map.put(Constant.CODE, "0");
   map.put(Constant.MESSAGE, "success");
   logger.info("城市自定义区域人口数据保存完成");
   return JSON.toJSONString(map);
}

BufferedReader

知识点: BufferReader 、Reader、File、FileInputStream

主要对IO的理解不够深刻。那么,需要认真的看一看io了。



猜你喜欢

转载自blog.csdn.net/starry_xiao/article/details/77482451