从文件读取类的对象数组

时间:2018-08-17 00:17:02

标签: java filereader

我有一类三个字段,两个int和一个double。我已经列出了我的类对象,并希望使用ScannerBufferedReaderFileReader从文本文件中逐行读取数组的对象。

MWE:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Model {
    public static final int Y = 7;
    public static final int K = 42;
    public static final int G = 3;

public static class Sleg {
        // private int id;
        private int i;
        private int j;
        private double l;

        public Sleg(int i, int j, double l) {
            // this.id = id;
            this.i = i;
            this.j = j;
            this.l = l;
        }

        @Override
        public String toString() {
            return Integer.toString(i) + " " + Integer.toString(j) + " " + Double.toString(l);
        }
    }


    public static void dataGen() {

        System.out.print("slegs = ");


          /*List<Sleg> slegs = Arrays.asList(); I want to write it like this and 
          read it from slFile.txt instead of the following line where the slegs are put one by one.*/
        List<Sleg> slegs = Arrays.asList(new Sleg(1,2,400),new Sleg(2,5,800),new Sleg(5,7,450),new Sleg(2,3,800),new Sleg(3,6,500),new Sleg(3,4,500),new Sleg(4,5,500),new Sleg(7,5,450),new Sleg(5,4,500),new Sleg(4,3,400),new Sleg(6,3,550),new Sleg(3,2,700),new Sleg(2,1,400), new Sleg(5,2,800));

        System.out.print(slegs);
        System.out.println("]");

        System.out.print("slegs = [");
        for (Sleg s : slegs) {
            System.out.print(s);
        }
        System.out.println("]");

        System.out.print("slegs = [");
        Sleg list2[] = new Sleg[slegs.size()];
        list2 = slegs.toArray(list2);

        File slFile = new File("slFile.txt");
        try {
            Scanner in7 = new Scanner(new BufferedReader(new FileReader("slFile.txt")));

            while(in7.hasNextLine()) {
                for (int sl = 0; sl < list2.length; sl++) {
                    String[] line = in7.nextLine().trim().split(" ");
                    list2[sl] = Double.parseDouble(line);                
                }
            }

        } catch (FileNotFoundException e) {
            System.out.println("Unable to read : " + slFile.toString());
        }

        for (Sleg i : list2) {
            System.out.print(i);
        }
        System.out.println("]");

        System.out.print("slegs = [");
        Object[] ss = slegs.toArray();
        for (int i = 0; i < ss.length; i++) {
            System.out.print(ss[i]);
        }
        System.out.println("]");


          int[][] u = new int [slegs.size()][G];
    }
}
slFile.tex中的

数据:

1 2 400
2 5 800
5 7 450
2 3 800
3 6 550
3 4 500
4 5 500
7 5 450
5 4 500
4 3 400
6 3 550
3 2 700
2 1 400
5 2 800

但是,弹出错误“将行更改为String”。如果我有一个3维数组,而不是包含3个字段的Sleg类的slegs对象,我知道如何读取文件,但是对此,我没有任何想法。 非常感谢您的想法!

3 个答案:

答案 0 :(得分:1)

您提供的代码存在一些问题。您尝试将#include <iostream> #include <vector> std::string build() { std::vector<std::string> data; data.push_back("One"); data.push_back("1"); const std::string token = "%s"; const std::string description = "This %s is number %s"; std::string out = ""; size_t start = 0; size_t end = description.find(token); int i = 0; while (end != std::string::npos) { out += description.substr(start, end - start); out += data[i++]; start = end + token.length(); end = description.find(token, start); } out += description.substr(start, end - start); return out; } int main () { std::cout << build() << '\n'; return 0; } This One is number 1 一起使用,假设文本文件中的行数,Boolean.parseBoolean(String)变量的类型为String[],但您重新尝试为其元素和其他各种事物分配一个list2

假设您只是想将文件读入Sleg[]对象的列表中,则可能需要执行以下操作:

double

答案 1 :(得分:1)

好吧,我使用LinkedList是因为我不知道那里有多少个项目/行(我本可以算出它们,但是如果没有指示有多少行,即第一行指示项目数) ...我将使用链接列表)。现在,您的方法dataGen将返回一个LinkedList存储Sleg对象的对象。这是有效的MVCE:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.LinkedList;
import java.util.Scanner;

public class Model {

    public static final int Y = 7;
    public static final int K = 42;
    public static final int G = 3;

    public Model() {

        dataGen();
    }

    public LinkedList<Sleg> dataGen() {
        LinkedList<Sleg> data = new LinkedList<>();
        File slFile = new File("slFile.txt");
        try {
            Scanner in7 = new Scanner(new BufferedReader(new FileReader("slFile.txt")));
            while (in7.hasNextLine()) {
                //get current line and split it via a space.
                String[] split = in7.nextLine().split(" ");
                int x = Integer.parseInt(split[0]);
                int y = Integer.parseInt(split[1]);
                double z = Double.parseDouble(split[2]);
                Sleg newItem = new Sleg(x, y, z);//new entry.
                data.add(newItem);//add as an entry to data.
            }
            in7.close();//should have this!!!
        } catch (FileNotFoundException e) {
            System.out.println("Unable to read : " + slFile.toString());
        }
        for (Sleg current : data) {
            System.out.println(current.toString());
        }
        return data;
    }

    public static void main(String[] args) {
        new Model();
    }

    class Sleg {

        int x = 0;
        int y = 0;
        double z = 0;

        Sleg(int x, int y, double z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        @Override
        public String toString() {
            return "(" + x + ", " + y + ", " + z + ")";
        }
    }
}

答案 2 :(得分:1)

问题在这里:

Double.parseDouble(line)
  1. 您无法将字符串数组解析为双精度型:Sleg

  2. 您也不能为对象引用分配双精度字(即:list2[sl] = Double.parseDouble(line)):String[] line = in7.nextLine().trim().split(" ");

  3. 读取下一行的操作应放在外部while循环中:for

  4. list2循环是不必要的,因为每个循环周期只处理一个元素(不是int sl = 0; while(in7.hasNextLine() && sl < list2.length) { String[] line = in7.nextLine().trim().split(" "); if (line.length < 3) { System.out.println("invalid line: " + line); continue; } list2[sl] = new Sleg( Integer.parseInt(line[0]), Integer.parseInt(line[1]), Double.parseInt(line[2]) ); sl++; } 中的所有元素)。

基于上述内容,可以将其修改为:

create type Customer_t as object(
   cid char(6),
   cusname varchar(15),
   birthdate date,
   phone char(10),
   address varchar(50)
);

create type claim_t as object(
   claimno char(12),
   cdate date,
   amount number(8,2),
   claimant ref customer_t
);

create type Claim_ntab is table of claim_t;

create type policy_t as object(
    pid char(7),      
    sdate date,
    edate date,
    inscar ref car_t,
    premium number(6,2),
    claims claim_ntab
);

create table Policies of policy_t(
pid primary key,
inscar references Cars
)nested table claims store as  claims_ntable;