如何 trim 在将元素分配到数组列表之前?

How to trim the elements before assigning it into an array list?

我需要将 CSV 文件中存在的元素分配到数组列表中。 CSV 文件包含扩展名为 .tar 的文件名。在将其读入数组列表或 trim 整个数组列表之前,我需要 trim 这些元素。请帮助我

try
   {
    String strFile1 = "D:\Ramakanth\PT2573\target.csv";  //csv file containing data
    BufferedReader br1 = new BufferedReader( new FileReader(strFile1)); //create BufferedReader 
    String strLine1 = "";
    StringTokenizer st1 = null;

    while( (strLine1 = br1.readLine()) != null) //read comma separated file line by line
    {
     st1 = new StringTokenizer(strLine1, ","); //break comma separated line using ","

     while(st1.hasMoreTokens())
     {
      array1.add(st1.nextToken()); //store csv values in array
     }
    }
   }
   catch(Exception e)
   {
    System.out.println("Exception while reading csv file: " + e);                  
   }

如果您想从您的标记中删除“.tar”字符串,您可以使用:

String nextToken = st1.nextToken();
if (nextToken.endsWith(".tar")) {
    nextToken = nextToken.replace(".tar", "");
}
array1.add(nextToken);

您不应该使用 StringTokenizer the JavaDoc says (in part) StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead. You should close your BufferedReader. You could use a try-with-resources statement to do that. And, you might use a for-each loop to iterate the array produced by String.split(String) 下面的正则表达式可以选择匹配 , 之前或之后的空格,如果 token endsWith,您可能 continue 循环".tar" 喜欢

String strFile1 = "D:\Ramakanth\PT2573\target.csv"; 
try (BufferedReader br1 = new BufferedReader(new FileReader(strFile1)))
{
  String strLine1 = "";
  while( (strLine1 = br1.readLine()) != null) {
    String[] parts = strLine1.split("\s*,\s*");
    for (String token : parts) {
      if (token.endsWith(".tar")) continue; // <-- don't add "tar" files.
      array1.add(token);
    }
  }
}
catch(Exception e)
{
  System.out.println("Exception while reading csv file: " + e);                  
}
while(st1.hasMoreTokens())
{
    String input = st1.nextToken();
    int index = input.indexOf(".");  // Get the position of '.'

    if(index >= 0){     // To avoid StringIndexOutOfBoundsException, when there is no match with '.' then the index position set to -1.
        array1.add(input.substring(0, index)); // Get the String before '.' position.
    }
}
if(str.indexOf(".tar") >0)
str = str.subString(0, str.indexOf(".tar")-1);