我需要将CSV文件中的元素分配到arraylist中。 CSV文件包含扩展名为.tar的文件名。在将其读入数组列表或修剪整个arraylist之前,我需要修剪这些元素。请帮帮我
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);
}
答案 0 :(得分:0)
如果你想删除" .tar"来自你的代币的字符串,你可以使用:
String nextToken = st1.nextToken();
if (nextToken.endsWith(".tar")) {
nextToken = nextToken.replace(".tar", "");
}
array1.add(nextToken);
答案 1 :(得分:0)
你不应该使用StringTokenizer
JavaDoc说(部分) StringTokenizer
是一个遗留类,出于兼容性原因而保留,尽管在新代码中不鼓励使用它。建议所有寻求此功能的人使用split
String
方法或java.util.regex
包。您应关闭BufferedReader
。您可以使用try-with-resources
statement来执行此操作。并且,您可以使用for-each
loop来迭代由String.split(String)
生成的数组,下面的正则表达式可选地匹配,
之前或之后的空格,如果是continue
,您可以token
循环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);
}
结束&#34; .tar&#34;喜欢
{{1}}
答案 2 :(得分:0)
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.
}
}
答案 3 :(得分:0)
if(str.indexOf(".tar") >0)
str = str.subString(0, str.indexOf(".tar")-1);