我正在尝试从文本文件中分割一行。正在从库存系统导入文本文件,我不知道如何使用表格格式对其进行格式化。我无法告诉你文件中的内容,但我会解释我在说什么。保密...
第1行:
名称订单sorder assemblyID desc date
123 123 123 1-2-3 123-456-789 12-3 1 \ 2 \ 3
第2行:
123 123 123 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);
}
答案 0 :(得分:2)
如果您某些只有一列会有额外的空格,并且始终是同一列,您仍然可以使用拆分,但您会做某事像这样:
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
答案 1 :(得分:0)
如果您知道问题仅在描述中,那么测试数组的长度。然后将数组从索引5连接到数组lenght - 1。 KitDate将是数组的最后一个字段。