改了 n 遍,就是不对,SOS😭
package zh.codegym.task.task18.task1827;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
reader.close();
if (args.length<4) return;
switch (args[0]) {
case "-c":
String id = generateId(fileName).substring(0, 8);
String name = getName(args).substring(0, 30);
String price = args[args.length-2].substring(0, 8);
String number = args[args.length-1].substring(0, 4);
if (!Product.verify(id, name, price, number)) return;
Product product = new Product(id, name, price, number);
FileOutputStream output = openFile(fileName);
output.write((product+"\n").getBytes());
output.close();
break;
}
}
public static String getName(String[] list) {
StringBuilder name = new StringBuilder();
for (int i = 1; i<list.length-2; i++) {
if (i!=1) name.append(" ");
name.append(list[i]);
}
return name.toString();
}
public static FileOutputStream openFile(String fileName) throws IOException {
List<String> productSList = new ArrayList<>();
BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
while (fileReader.ready()) {
productSList.add(fileReader.readLine()+"\n");
}
fileReader.close();
FileOutputStream output = new FileOutputStream(fileName);
for (String productS: productSList) {
output.write(productS.getBytes());
}
return output;
}
public static String generateId(String fileName) throws IOException {
int maxId = 0;
try (Scanner scanner = new Scanner(new FileInputStream(fileName));) {
while (scanner.hasNextLine()) {
String data = scanner.nextLine();
int id = Integer.parseInt(data.substring(0, 8).trim());
if (id>maxId) maxId = id;
}
}
return String.valueOf(maxId+1);
}
}
class Product {
private String id;
private String name;
private String price;
private String number;
public Product(String id, String name, String price, String number) {
this.id = id;
this.name = name;
this.price = price;
this.number = number;
}
public static boolean verify(String id, String name, String price, String number) {
try {
Integer.parseInt(id);
Double.parseDouble(price);
Integer.parseInt(number);
return true;
} catch (Exception e) {
return false;
}
}
public Integer getId() {
return Integer.parseInt(id);
}
public String toString() {
return String.format("%-8s%-30s%-8s%-4s", id, name, price, number);
}
}