使用java将.txt文件转换为.cvs文件?

时间:2015-05-12 07:26:27

标签: java

我有一个文本文件。

Date    Order ID    SKU Transaction type    Payment Type    Payment Detail  Amount  Quantity    Product Title

11-May-15   171-4579244-1779543 NT52-178    Refund  Amazon fees Commission  Rs. 49.32       Masha Women's Cotton Nighty NT52-178

11-May-15   171-4579244-1779543 NT52-178    Refund  Amazon fees Fixed closing fee   Rs. 11.24       Masha Women's Cotton Nighty NT52-178

11-May-15   171-4579244-1779543 NT52-178    Refund  Amazon fees Shipping holdback   Rs. 3.71        Masha Women's Cotton Nighty NT52-178

11-May-15   171-4579244-1779543 NT52-178    Refund  Product charges     Rs.
-399.00 1   Masha Women's Cotton Nighty NT52-178

我想将其转换为CSV文件。

我正在使用以下代码

   File file = new File("/Users/manish/Documents/New folder/report.txt");
       StringBuffer str = new StringBuffer();
       BufferedReader br = null;

        try
       {
            br = new BufferedReader(new FileReader(file));
            String text = null;

            // repeat until all lines is read
            while ((text = br.readLine()) != null)
            {
                    String splitarray[] = text.split("  ");
                    String Date = splitarray[0];
                    String Order_ID = splitarray[1]; // line 42
                    String sku = splitarray[2];
                    String Transaction_type = splitarray[3];
                    String Payment_type = splitarray[4];
                    String Payment_detail = splitarray[5];
                    String amount = splitarray[6];
                    String Quantity = splitarray[7];
                    String Product_title = splitarray[8];
                    System.out.println(Date+ " " + Order_ID);

            }
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                if (br != null)
                {
                    br.close();
                }
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }

        // show file contents here
        System.out.println(str.toString());

但是它给出了错误

  

线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:1         at test_pract.TEST_pract.main(TEST_pract.java:42)       Java结果:1

1 个答案:

答案 0 :(得分:1)

问题是你的行, 那么你的splitarray []是空的,并且不可能使用splitarray [1]。

您可以使用if语句对其进行排序:

if(!text.equals("")) {
   splitarray[] ....
}

你有另一个问题:你用2个空格分开, 如果你的文本中有4个空格(并且你的例子中有),那么你在Splitarray中得到一个空字符串,因为它在这4个空格之间分裂。然后你会得到每行不同的数组。

你应该消除这些或使用更好的拆分参数,如:

text.replace("    ", "  ")  

text.split("    |  ")

最后一个会尝试在4个空格中分割,或者在2个空格处找不到。