如果文件java中有多个(\ t),则StringTokenizer从下一行开始

时间:2012-08-16 11:13:14

标签: java file stringtokenizer

我在\t基础上解析文件数据,如果找到多个\t开始从下一个新行解析并从0开始arraylist单词,我想要的是什么。

public static void readFile() throws IOException {
  String line;
  ArrayList<String> words = new ArrayList<String>();

  try {
    BufferedReader inFile = new BufferedReader (new FileReader ("/weather.txt"));

    while ((line = inFile.readLine()) != null) {
      StringTokenizer token= new StringTokenizer(line,"\t");
      while (token.hasMoreTokens()) {   
        words.add(token.nextToken());
      }

      /*
       * function to print the values
       */                   
      getMetadataTriple(words);
    }
  }

1 个答案:

答案 0 :(得分:0)

尝试以下正则表达式解决方案:

public static void readFile() throws IOException
{
    String line;
    ArrayList<String> words = new ArrayList<String>();    
    try
    {
        BufferedReader inFile = new BufferedReader(new FileReader("weather.txt"));

        while ((line = inFile.readLine()) != null)
        {
            String[] temp = line.split("\\t");
            for (String s : temp)
            {
                if(!s.isEmpty())
                {
                    words.add(s);
                }
                else //another \t
                {
                    words.clear();
                    break;
                }   
            }

            /*
             * function to print the values
             */
            getMetadataTriple(words);
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

}