簡體   English   中英

Java .split()無法正常工作

[英]Java .split() not working

我正在嘗試從文本文件中拆分一行。 該文本文件是從庫存系統中導入的,我不知道如何使用表格格式對其進行格式化。 我無法告訴您文件中包含的內容,但我會解釋我在說什么。 保密...

第1行:

名稱順序順序AssemblyID描述日期

123123123 1-2-3 123-456-789 12-3 1 \\ 2 \\ 3

第2行:

123123123 1-2-3 123-456-789 12 3 1 \\ 2 \\ 3

如果您看到...說明欄內有一個空格。 這意味着它將把它分配到我數組的單獨部分。 第一個數組的大小為7,但第二個數組的大小為8。這就是我所擁有的。

public static void main(String[] args) throws IOException, ParseException {

    ArrayList < CustordData > list = new ArrayList < CustordData > ();
    CustordData cd = new CustordData();
    int[] array = new int[10];
    DateFormat format = new SimpleDateFormat("MM/dd/Y");

    try {
      String read = null;
      BufferedReader in = new BufferedReader(new FileReader("Custord.txt"));
      while ((read = in .readLine()) != null) {
        String[] splited = read.split("\\s+");
        cd.setCustName(splited[0]);
        cd.setPurchaseOrder(splited[1]);
        cd.setSalesOrder(splited[2]);
        cd.setAssemblyID(splited[4]);
        cd.setOrderDesc(splited[5]);
        cd.setKitDate(format.parse(splited[6]));
      }
      for (CustordData d: list) {
        System.out.println(d.getCustName() + d.getPurchaseOrder() + d.getSalesOrder() + d.getAssemblyID() + d.getOrderDesc() + d.getKitDate() + d.getShipDate() + d.getPricePer() + d.getTotal());
      }

    } catch (IOException e) {
      System.out.println("There was a problem: " + e);
    }

如果確定只有一列具有多余的空格,並且始終是同一列 ,則仍然可以使用split,但是您可以這樣做:

Let N be the index of the description column, 
Assign columns [1, N-1] to the data you need
Assign columns [N, TotalColumns - 1] to description
Assign column TotalColumns to date

像這樣:

   public static void main(String[] args) {
   String noSpaces = "123 123 123 1-2-3 123-456-789 12-3 1\\2\\3";
   String withSpaces = "123 123 123 1-2-3 123-456-789 12 3 1\\2\\3";

   String[] splitNoSpaces = noSpaces.split("\\s+");
   printData(splitNoSpaces);

   String[] splitWithSpaces = withSpaces.split("\\s+");
   printData(splitWithSpaces);

}

private static void printData(String[] data)
{
    int totalColumns = data.length;

    System.out.println("Name: " + data[0]);
    System.out.println("Order: " + data[1]);
    System.out.println("SOrder: " + data[2]);
    System.out.println("AssemblyID: " + data[3]);
    System.out.print("Description: ");
    for(int i = 4; i < totalColumns - 2; i++)
    {
        System.out.print(data[i] + " ");
    }
    System.out.println();
    System.out.println("AssemblyID: " + data[totalColumns - 1]);
}

產量:

Name: 123
Order: 123
SOrder: 123
AssemblyID: 1-2-3
Description: 123-456-789 
AssemblyID: 1\2\3
Name: 123
Order: 123
SOrder: 123
AssemblyID: 1-2-3
Description: 123-456-789 12 
AssemblyID: 1\2\3

如果您只知道描述中存在問題,則測試數組長度。 然后將數組從索引5連接到數組長度-1。KitDate將是數組的最后一個字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM