读取文件并将其存储在数组中,然后在有}的地方将文件拆分, [英] Reading a file and storing it in an array, then splitting up the file everywhere there is a },

查看:104
本文介绍了读取文件并将其存储在数组中,然后在有}的地方将文件拆分,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一个文件并将其存储在数组中,然后在有}的位置将其拆分,以便数组中的每个项目都包含拆分后的字符串.这就是我的意思,

I want to Read a file and store it in an array, then split up the array everywhere there is a }, so that each item in the array contains the string split up. Here is what I mean,

我的文件包含以下内容:

My file contains stuff like this:

[
{
    "sample1": {
        "color": "red", 
        "date": "2011, 
        "name": "george"
    }
}, 
{
    "sample2": {
        "color": "red", 
        "date": "2012", 
        "name": "phil"
    }
}, 

我想阅读此文件,例如在数组中具有oth元素来表示

I want to read this file, have have for example the oth element in the array to represent

{
        "sample1": {
            "color": "red", 
            "date": "2011, 
            "name": "george"
        }
}, 

并用第一个元素表示

    {
    "sample2": {
        "color": "red", 
        "date": "2012", 
        "name": "phil"
    }
}, 

现在我不太确定该怎么做,我不知道数组的大小,也不确定如何访问数组的每个元素,到目前为止,我已经开始了

Now I am not too sure how to do this, I don't know what the size of my array will be and I am not sure how I will access each element of my array, I have started off with this so far

String str;
  char[] getArray;

  FileReader fr = new FileReader("/sampleProject");
  BufferedReader br = new BufferedReader(fr);

  br.readLine();

  while ((str = br.readLine()) != null) {
     str.toCharArray();
     str.split("},");

  }

  System.out.println("Here it is" + str);

  br.close();
}

推荐答案

如果您不知道数组的大小,则可以使用ArrayList. str.toCharArray();str.split("},")};可能未达到预期的效果,因为您从未分配返回的值.

If you don't know, what size an array is you can use ArrayList. str.toCharArray(); and str.split("},")}; probably don't do what you expect, since you never asign the returned value.

我没有对此进行测试,但是也许它可以满足您的需求:

I didn't test this, but maybe it does what you need:

String str;
  char[] getArray;

  FileReader fr = new FileReader("/sampleProject");
  BufferedReader br = new BufferedReader(fr);

  br.readLine();
  ArrayList<String> result = new ArrayList<>();

  while ((str = br.readLine()) != null) {
     String[] array = str.split("},");
     for(int i = 0; i< array.length;i++) {
         result.add(array[i]);
     }
  }

  System.out.println("Here it is" + str);

  br.close();

这篇关于读取文件并将其存储在数组中,然后在有}的地方将文件拆分,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆