通过txt文件将对象创建为Java中的数组
我想完成一个小程序。
我有一个文本文件(.txt)来存储我所拥有的对象的不同数据。
文件的结构是下一个(例如data.txt):
- Sedane
- 2005年
- 195000
- 柴油机
- 蓝色
- SUV
- 2013
- 34000
- 汽油
- 黑色
每个对象都是真正的一个我称之为Cars的类。 因此1线是汽车的类型,第2年是建造的,第3线是milage,第4线是燃料的类型,第5线是汽车的颜色。
所以基本上我需要打开文件,并在我将程序执行到包含对象的数组中时将数据加载到内存中。
我可以打开文件但是在读取数据并将其放入数组时我被阻止了。
对于这个例子,数组大小为2,但是如果我在文件中有更多条目,它将在程序启动时加载它的大小。
这就是我现在的unti(对于我的代码……)
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 !" ); } }
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
你也必须处理exception,在try catch
结构中包围东西。
像这样的人会这样做。 我将文件内容逐行添加到Arraylist而不是数组。 这样你就不必知道你的数组需要多大。 此外,您可以随时将其更改为数组。
public ArrayList readFileToMemory(String filepath) { in = new BufferedReader(new FileReader( "data.txt" )); String currentLine = null; ArrayList fileContents = new ArrayList (); 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; }
您可以在下面查看我的解决方案(我还更正/简化了用于读取文件的变量的一些问题,无论如何这不是主题):
public static void loadCars() { FileReader fopen; BufferedReader opened; String line; ArrayList carList = new ArrayList (); 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 !"); } }
基本上我们使用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]; } }
但我要说这可能是一个“太静态”。 为简单起见,我假设您的所有字段都是String类型,但可能像’year’或’milage’这样的字段可能是int类型。 在这种情况下,您可以使用Object [](而不是String [])的数组,然后使用正确的类型转换值。
我希望这可以帮到你。