如何从 .txt 文件中读取数据并将数据放入对象的数组列表中?
问题描述:
到目前为止我所写的内容是根据我目前对基本数组的了解,但我只是不明白如何使用数组列表,或者如何从文件中读取.到目前为止我写的东西有效.任何帮助修复我的代码以从文件中读取并使用数组列表的链接或建议将不胜感激.谢谢.
What I have written so far works from my current knowledge of basic arrays, but I just don't understand how to use an arraylist, or how to read from a file. What I have written so far works. Any links or advice to help fix my code to read from a file and use an arraylist would be greatly appreciated. Thank you.
public class TestPackages
{
public static void main (String[] args)
{
Packages testPackages = new Packages();
testPackages.addPacket(1001, 7.37, "CA");
testPackages.addPacket(1002, 5.17, "CT");
testPackages.addPacket(1003, 11.35, "NY");
testPackages.addPacket(1004, 20.17, "MA" );
testPackages.addPacket(1005, 9.99, "FL");
testPackages.addPacket(1006, 14.91, "VT");
testPackages.addPacket(1007, 4.97, "TX");
System.out.println(testPackages);
}
}
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Packages
{
private Packet[] shipment;
private int count;
private double totalWeight;
public Packages()
{
shipment = new Packet[100];
count = 0;
totalWeight = 0.0;
}
public void addPacket (int idNumber, double weight, String state)
{
if(count == shipment.length)
increaseSize();
shipment[count] = new Packet (idNumber, weight, state);
totalWeight += weight;
count++;
}
public String toString()
{
String report;
report = "All Packets\n";
for(int num = 0; num < count; num++)
report += shipment[num].toString() + "\n";
report += "Total Weight:\t" +totalWeight+" pounds";
return report;
}
private void increaseSize()
{
Packet[] temp = new Packet[shipment.length * 2];
for (int num = 0; num < shipment.length; num++)
temp[num] = shipment[num];
shipment = temp;
}
}
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
public class Packet
{
private int idNumber;
private double weight;
private String state;
public Packet(int idNumber, double weight, String state)
{
this.idNumber = idNumber;
this.weight = weight;
this.state = state;
}
public boolean isHeavy(double weight)
{
return (weight > 10);
}
public boolean isLight(double weight)
{
return (weight < 7);
}
public String toString()
{
String description = "ID number: " + idNumber + "\tWegiht: " + weight + "\tState: "
+ state;
return description;
}
}
答
java 中有多种逐行读取文件的方法.但我更喜欢使用 commons-io 实用程序.这是一个非常有用的工具,可以从文件中读取.这是一个单行示例.
There are many ways to read a file line by line in java. But I prefer using commons-io utils. It's a very useful tool that provide reading from a file. Here is a one line example.
List<String> lines = FileUtils.readLines(new File(fileName));