我正在尝试从文本文件中拆分一行。该文本文件是从清单系统导入的,我不知道如何使用表格格式对其进行格式化。我无法告诉您文件中包含的内容,但我会解释我在说什么。保密...
第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