Java-从文件读取数据转换初始化对象

Java-Reading from a file to initalize an object with data conversion

我有这个文件:"Test.txt" -> 1,cont,details,950.5,asd

我的Class是Auto,构造函数是int, string, string, double, string

我如何读取此文件,然后使用正确的数据转换来初始化我的对象?

我想我也需要使用逗号分隔符。

    FileReader inFile2=null;
    BufferedReader outBuffer2=null;
    inFile2=new FileReader("Test.txt");
    outBuffer2 = new BufferedReader(inFile2);
    List<String> lines = new ArrayList<String>();
    String line="";

    while((line = outBuffer2.readLine()) != null) {
        lines.add(line);
        System.out.println(lines);
    }
    outBuffer2.close();
    inFile2.close();

    // 

    String[] splitTranzactie = lines.toArray(new String[]{});
    Auto t = new Auto(Int32(splitTranzactie[0]), splitTranzactie[1], splitTranzactie[2],
        ToDouble(splitTranzactie[3]), splitTranzactie[4]);

对于 int 你可以使用

int a = Integer.parseInt(string);

双倍几乎相同

double b = Double.parseDouble(string);

但请注意,如果字符串不符合预期,两者都可能抛出 NumberFormatException。

您可以从行创建流,然后您可以应用

Function(ArrayList< String >,ArrayList< Auto >)

接口通过 lambda 函数定义自定义行为来获取数据.要将数据从字符串转换为整数,请使用 Integer.parse(String),对于双精度数据,请使用 Double.parse(string)

使用 Java 8 流:

 try (Stream<String> fileStream = Files.lines(Paths.get("Test.txt"))) {
        fileStream.map(line -> line.split(",")).forEach(array -> {
            Auto auto = new Auto(Integer.parseInt(array[0]), array[1], array[2], Double.parseDouble(array[3]), array[4]);
        });
    }

您可以通过以下方式收集汽车列表:

    List<Auto> autoList;
    try (Stream<String> fileStream = Files.lines(Paths.get("Test.txt"))) {
        autoList = fileStream.map(line -> {
            String[] array = line.split(",");
            return new Auto(Integer.parseInt(array[0]), array[1], array[2], Double.parseDouble(array[3]), array[4]);
        }).collect(Collectors.toList());
    }

这里有一些问题。首先:

 String[] splitTranzactie = lines.toArray(new String[]{});

只是将您的行列表变成行数组。要将每一行拆分成它的组成部分,您可以使用 String.split(",") 之类的东西。这将 return 一个字符串数组。请注意,如果您希望最后一个值中的任何一个为空,即以一个或多个逗号结尾,那么 returned 数组将与它找到的最后一个值位置一样长。也就是说,如果该行是 1,cont,details,,,您将拆分 return 一个长度为 3 而不是 5 的数组。您应该对此进行防御性编码。

要将 String 转换为 int 或 double,您可以分别使用 Integer.parseInt()Double.parseInt()。同样,如果值可能不是数值,您可能需要考虑防御性编码,因为如果这两种方法无法解析输入,它们将抛出异常。

您还应该将 close() 方法放在 finally 块中以确保它们被调用,但是由于它们是 AutoCloseable 您可以通过使用 try-with-resources 语法完全避免这种情况将自动关闭reader。

    try(Reader in = new Reader()) {
    }

一个包含以上所有内容(但没有任何防御代码)的工作示例可能如下所示:

        List<Auto> autos = new ArrayList<>();
        try (BufferedReader in = new BufferedReader(new FileReader("Test.txt"))) {
            String line = null;
            while((line = in.readLine()) != null) {
                String[] values = line.split(",");
                autos.add(new Auto(
                        Integer.parseInt(values[0]),
                        values[1],
                        values[2],
                        Double.parseDouble(values[3]),
                        values[4]));
            }
        }

按照你目前的方案,这是我可能执行任务的一种方式。如果这些验证失败,代码还会验证数据并放置默认值。

public List<Auto> getAutoListFromFile(String filePath) {
    List<Auto> list = new ArrayList<>(); // Declare a List Interface
    Auto auto;  // Declare Auto
    // Open a file reader. Try With Resourses is used here so as to auto close reader.
    try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
        String line = "";
        // Iterate through the file lines
        while((line = reader.readLine()) != null) {
            line = line.trim(); // Trim lines of any unwanted leading or trailing whitespaces, tabs, etc.
            // Skip blank lines.
            if (line.equals("")) {
                continue;
            }
            System.out.println(line); // Display file line to console (remove if desired).
            /* Split the current comma delimited file line into specific components.
               A regex is used here to cover all comma/space scenarios (if any). */
            String[] lineParts = line.split("\s{0,},\s{0,}");
            // Establish the first Auto memeber value for the Auto class constructor. 
            int id = -1;  // default
            // Make sure it is an unsigned Integer value. RegEx is used here again.
            if (lineParts[0].matches("\d+")) {
                id = Integer.parseInt(lineParts[0]);
            }
            // Establish the second Auto memeber value for the Auto class constructor.
            String cont = !lineParts[1].equals("") ? lineParts[1] : "N/A";  //Ternary Used
            // Establish the third Auto memeber value for the Auto class constructor.
            String details = !lineParts[2].equals("") ? lineParts[2] : "N/A";  //Ternary Used
            // Establish the fourth Auto memeber value for the Auto class constructor.
            double price = 0.0d;  //default
            // Make sure it is a signed or unsigned Integer or double value. RegEx is used here again.
            if (lineParts[3].matches("-?\d+(\.\d+)?")) {
                price = Double.parseDouble(lineParts[3]);
            }
            // Establish the fifth Auto memeber value for the Auto class constructor.
            String asd = !lineParts[4].equals("") ? lineParts[4] : "N/A"; //Ternary Used
            auto = new Auto(id, cont, details, price, asd); // Create an instance of Auto
            list.add(auto); // Add Auto instance to List.
            // Go and read next line if one exists
        }   
    }
    // Handle Exceptions.
    catch (FileNotFoundException ex) {
        Logger.getLogger("getAutoListFromFile() Method Error!").log(Level.SEVERE, null, ex);
    }
    catch (IOException ex) {
        Logger.getLogger("getAutoListFromFile() Method Error!").log(Level.SEVERE, null, ex);
    }
    return list;  // Return the filled list.
}

要使用此方法,您可以这样做:

List<Auto> list = getAutoListFromFile("Test.txt");