在Java中通过txt文件将对象创建到数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23145416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:03:04  来源:igfitidea点击:

Creating objects via txt file into an array in Java

javaarraysobject

提问by Cyberflow

I am trying to complete a little program.

我正在尝试完成一个小程序。

I've got a text file (.txt) to store different data on objects that i've got.

我有一个文本文件 (.txt) 来存储我拥有的对象的不同数据。

The structure of the file is the next (exemples data.txt) :

文件的结构如下(例如data.txt):

  • Sedane
  • 2005
  • 195000
  • Diesel
  • Blue
  • SUV
  • 2013
  • 34000
  • Fuel
  • Black
  • 轿车
  • 2005年
  • 195000
  • 柴油机
  • 蓝色
  • 越野车
  • 2013年
  • 34000
  • 燃料
  • 黑色的

Each object is made true a class that i've build called Cars. So the 1 line is the type of car, the 2nd the year of built, the 3rd line is the milage, the 4th is the type of fuel, and the 5th line is the color of the car.

每个对象都变成了一个我已经构建的名为 Cars 的类。所以第1行是汽车类型,第2行是建造年份,第3行是里程数,第4行是燃料类型,第5行是汽车的颜色。

So basicly i need to open the file, and load the data into the memory when i execute my program into an array with object in it.

所以基本上我需要打开文件,并在我将程序执行到一个包含对象的数组中时将数据加载到内存中。

I'm ok to open the file but i'm blocked when it comes to reading the data and putting it in an array.

我可以打开文件,但是在读取数据并将其放入数组时我被阻止了。

The array size is 2 for this exemple, but if i have more entries in the file it's going to adapt it's size when loading at the startup of the program.

这个例子的数组大小是 2,但是如果我在文件中有更多的条目,它会在程序启动时加载时调整它的大小。

Here's what i've got unti now (for my code ...)

这是我现在所拥有的(对于我的代码......)

public static void loadCars () {
    FileReader fopen;
    BufferedReader opened;
    String line;

    try {
        fEntree = new FileReader( "data.txt" );
        opened = new BufferedReader( fopen );
        while ( opened.ready() ) {
            line = opened.readLine();
            // Don't know what to do here ????
        }
        opened.close();
    } catch ( IOException e ) {
        System.out.println( "File doesn't exist !" );
    }

}

采纳答案by Anubian Noob

LineNumberReader  lnr = new LineNumberReader(new FileReader(new File("File1")));
lnr.skip(Long.MAX_VALUE);

long length = lnr.getLineNumber();

lnr.close();

in = new BufferedReader(new FileReader( "data.txt" ));

Car[] cars= new Car[length/5];
String currentLine;
int i=0;

for(int i=0;i<length/5;i+=5) {
    String name = in.readLine();
    String year = in.readLine();
    String miles = in.readLine();
    String gas = in.readLine();
    String color = in.readLine();
    cars[i] = new Car(name,year,miles,gas,color);
}

You'll have to handle exceptions too, surround stuff in try catchstructures.

你也必须处理异常,在try catch结构中包围东西。

回答by WoDoSc

You can look at my solution here below (I also corrected/simplified some problems with the variables for reading the file, anyway this was not the main topic):

您可以在下面查看我的解决方案(我还纠正/简化了读取文件的变量的一些问题,无论如何这不是主要主题):

public static void loadCars() {
    FileReader fopen;
    BufferedReader opened;
    String line;

    ArrayList<Car> carList = new ArrayList<Car>();
    try {
        fopen = new FileReader("data.txt");
        opened = new BufferedReader(fopen);

        int nFields = 5; // we have 5 fields in the Car class
        String[] fields = new String[nFields]; // to temporary store fields values read line by line
        int lineCounter = 0;
        while ((line = opened.readLine()) != null) {
            fields[lineCounter] = line;
            lineCounter++;
            if ((lineCounter) % nFields == 0) { //it means we have all 5 fields values for a car
                carList.add(new Car(fields)); //therefore we create a new car and we add it to the list of cars
            }

        }
        opened.close();
    } catch (IOException e) {
        System.out.println("File doesn't exist !");
    }
}

Basically we use an ArrayList to store all the cars, and we read the file, waiting to have all the fields values in order to create the Car object. I store the fields values in an array of Strings: I don't know how you implemented the Car class, but maybe it is useful to create a constructor that takes as parameter an array of strings, so it can set the fields, for instance:

基本上,我们使用一个 ArrayList 来存储所有汽车,然后我们读取文件,等待所有字段的值以创建 Car 对象。我将字段值存储在一个字符串数组中:我不知道你是如何实现 Car 类的,但也许创建一个将字符串数组作为参数的构造函数很有用,例如,它可以设置字段:

class Car {

    private String type;
    private String year;
    private String milage;
    private String fuel;
    private String color;

    public Car(String[] fields) {
        type=fields[0];
        year=fields[0];
        milage=fields[0];
        fuel=fields[0];
        type=fields[0];
    }
}

But I've to say that probably this is a little 'too static'. For simplicity I assumed that all your fields are of String type, but probably fields like 'year' or 'milage' might be of int type. In this case you can use array of Object[] (instead of String[]), and then cast the value with the right type.

但我不得不说,这可能有点“过于静态”。为简单起见,我假设您的所有字段都是 String 类型,但可能像 'year' 或 'milage' 这样的字段可能是 int 类型。在这种情况下,您可以使用 Object[] 数组(而不是 String[]),然后使用正确的类型转换该值。

I hope this may help you.

我希望这可以帮助你。

回答by j.jerrod.taylor

Someting like this will do the trick. I'm adding the file contents line by line to an Arraylist instead of an array though. This way you don't have to know how big your array needs to be before hand. Plus you can always change it to an array later.

像这样的事情会成功。不过,我将文件内容逐行添加到 Arraylist 而不是数组。这样您就不必事先知道您的阵列需要多大。另外,您以后可以随时将其更改为数组。

public ArrayList<String> readFileToMemory(String filepath)
{
    in = new BufferedReader(new FileReader( "data.txt" ));
    String currentLine = null;
    ArrayList<String> fileContents = new ArrayList<String>();

    try
    {
        while((currentLine = in.readLine()) != null)
        {
            fileContents.add(currentLine);
        }
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            in.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }

    return fileContents;
}