【问题标题】:Split String and store in array拆分字符串并存储在数组中
【发布时间】:2017-03-07 08:58:52
【问题描述】:

我有 CSV 文件要读取,我存储在字符串中,我需要在每个 "," 处拆分字符串,我的输入会像

名称、ID、描述、emailId Micheal,234655,"下一行问题的测试说明 谢谢和问候,迈克”,Mike@yahoo.com

请帮我解决这个问题。

问候, 维杰

enter code here

import java.io.*;
import java.util.logging.*;
import java.util.ArrayList;
import java.util.List;
public class ReadingCSVFile {

 public static void main(String args[])
 {
    StringBuilder sb =new StringBuilder();
    int n;
    String inputStream;
    String Name[] =new String[30];
    List l1 = new ArrayList();
    try
    {
         FileInputStream fis =new  fileInputStream("C:/Users/vijaykumar.naga/Desktop/Abc.txt"); 
     FileOutputStream fos = new FileOutputStream("C:/Users/vijaykumar.naga/Desktop/Output.txt");
     int ch;
     while((ch = fis.read()) != -1){
         sb.append((char)ch);
     }
     System.out.println("The InputString is " +sb.toString());
     String abcd =sb.toString();
       for(int i=0; i<30; i++)
         {
         l1.add(abcd.split(","));
         System.out.println("The Names are " +l1);
          }

        }
    catch(Exception e)
     {

      }
    }

  }

【问题讨论】:

  • 目前的方法有什么问题
  • 因此您阅读了所有文件,并附加了一个 Stringbuilder。然后您将完整的结果按, 30 次拆分,并将相同的 String[] 值(不是相同的引用)添加到列表中。不确定您是否达到了预期
  • 文件包含多少行,一行或多行?编辑:我只是发布我自制的(基本)解析器。使用 Scanner 读取多行文件

标签: java


【解决方案1】:

我建议使用如下正则表达式:

([A-Za-z]+)\,(\d+)\,(\".+\"|.+)\,(\w+@\w+\.\w+)

【讨论】:

    【解决方案2】:

    这是我用来读取 CSV 文件的简单解决方案。

        Scanner sc = null;
        try {
            sc = new Scanner(new File("test.csv"));
            String s = null;
            String[] array;
            while(sc.hasNext()){
                s = sc.nextLine();
                array = s.split(",");
                System.out.println(Arrays.toString(array));
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } finally {
            if(sc != null) sc.close();
        }
    

    基本上,这将使用 Scanner 一次读取一行,可能不是最好的,但 40 行,我真的不在乎;)

    然后,我使用逗号分隔行,注意是否在值中使用,,此处不进行检查。

    然后,我在控制台中打印数组。

    编辑:

    try (Scanner sc = new Scanner(new File("test.csv"))){
            String s = null;
            String[] array;
            while(sc.hasNext()){
                s = sc.nextLine();
                array = s.split(",");
                // Do what you want with the array, here I just print the result
                System.out.println(Arrays.toString(array));
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    

    【讨论】:

    • Java 有 try-with-resources 5 年了,有些人仍然使用普通的try/catch 习惯用法来读取文件?
    • @Tom 原因很简单,办公室里还有 JAVA 6 ! :(但你是对的,我会编辑这个,你能验证一下吗,以防万一我
    • @Tom,另外,我可以为此使用 Stream API,但同样不能在这里测试。和 5 年?第一个版本有2年没有?
    • 您说的是 Java 8,但在 Java 7 中引入了 try-with-resources。顺便说一句,您不需要从 Scanner 中拆分文件实例化。所以try(Scanner sc = new Scanner(new File("test.csv")) 会很好。 “原因很简单,在办公室里还有在 JAVA 6” 太可悲了。真的。 Java 6 太旧了,无法继续使用它。
    • @Tom 是的,你又是对的,我在这里混合了我的版本,但又一次,Java 6 :( 这很痛苦,我什至开始忘记使用它们。只是为了历史,这是一家使用 JCAPS 的银行,银行很难更新他们的技术...... PS:欢迎您编辑我的答案,你知道。这里没有难过的感觉。
    【解决方案3】:

    你可以试试 split()

    使用下面的语法

    String[] parts = string.split(",");

    或者您可以使用带有标记的 StringTokenizer ,

    希望对你有帮助

    【讨论】:

    • 这并不能解决 value 中可能包含分隔符的问题。
    • 请以您的方式详细说明。我从我的水平尝试过
    【解决方案4】:

    请查看您的代码修订版并附上解释:

    import java.io.*;
    import java.util.logging.*;
    import java.util.ArrayList;
    import java.util.List;
    public class ReadingCSVFile {
    
     public static void main(String args[])
     {
        StringBuilder sb =new StringBuilder();
        int n;
        String inputStream;
        String Name[] =new String[30];
        List<String> l1 = new ArrayList<>(); //Use generics <> operator
        try
        {
             FileInputStream fis =new  fileInputStream("C:/Users/vijaykumar.naga/Desktop/Abc.txt"); 
         FileOutputStream fos = new FileOutputStream("C:/Users/vijaykumar.naga/Desktop/Output.txt");
         int ch;
         while((ch = fis.read()) != -1){
             sb.append((char)ch);
         }
         System.out.println("The InputString is " +sb.toString());
         String abcd =sb.toString();
           /*for(int i=0; i<30; i++)
             {
             l1.add(abcd.split(","));           //This is wrong. abcd.split(",") will return String[]
             System.out.println("The Names are " +l1);
              }
    
            }*****This loop is not needed*/ 
        //As you already read the content in abcd variable, do as follows
        l1.addAll(Arrays.asList(abcd.split(",")));
    
        catch(Exception e)
         {
    
          }
        }
    
      }
    

    【讨论】:

    • 他需要存储在数组中..不在列表中
    • 但是如果他将该行作为 String[] 存储到他的 List 中(就像在原始列表中一样),您可以在此处进行更多更改;)
    • @Karthik,如果您知道行数不是问题,但最好使用列表。最后,如果需要,请使用 toArray 方法。我猜 OP 更喜欢这种方法
    • 是的,完全正确.. 我同意@AxelH..如果你有列表,你可以将它转换成一个数组,在这种情况下,使用 List 更可取。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多