我正在尝试完成一个小程序。
我有一个文本文件(.txt)来存储我所拥有的对象的不同数据。
该文件的结构如下(例如 data.txt):
- Sedane
- 2005
- 195000
- Diesel
- Blue
- SUV
- 2013
- 34000
- Fuel
- Black
每个对象都是我构建的名为 Cars 的类。
因此,第 1 行是汽车类型,第 2 行是制造年份,第 3 行是里程,第 4 行是燃油类型,第 5 行是汽车颜色。
所以基本上我需要打开文件,并在将程序执行到其中包含对象的数组中时将数据加载到内存中。
我可以打开该文件,但在读取数据并将其放入数组时被阻止。
本例中数组大小为 2,但如果文件中有更多条目,它将在程序启动时加载时调整其大小。
这是我现在所拥有的(对于我的代码......)
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 !" );
}
}
像这样的事情就会成功。我将文件内容逐行添加到 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)