我正在创建一个加载文本文件的函数,问题是,不是你期望的文本文件格式(name | id | address | etc),它就像这样呈现;
Obe Two Canobi
专家
假
JK001
125
F010
任务
编程和计算机支持
关闭一个文本文件,我的程序必须能够加载任何数量的这组8.这是我想出的但是无论出于什么原因都不起作用,它将从第一个输入重新加载相同的行从我印刷的内容。
//Custom function to load files from given inputs
public static void loadFile(String location,String file,String type) {
//Using try/catch to retrieve errors
WorkUnit[] wu = null;
try {
//Using the buffered reader to load the file.
BufferedReader in = null;
try {
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("C:\\Users\\kenji\\IdeaProjects\\Assingment01C_LaTrobe\\src\\workunit.txt")));
lnr.skip(Long.MAX_VALUE);
int length = lnr.getLineNumber() + 1;
print(length + "");
lnr.close();
in = new BufferedReader(new FileReader( "C:\\Users\\kenji\\IdeaProjects\\Assingment01C_LaTrobe\\src\\workunit.txt" ));
wu = new WorkUnit[length/8];
print(wu.length + "");
String currentLine;
for(int i=0;i<length/8;i+=8) {
Crew cr = new Crew();
Ship ship = new Ship();
cr.setName(in.readLine());
cr.setClassification(getCrewClassification(in.readLine()));
cr.setStatus(getTrueFalse(in.readLine()));
cr.setId(in.readLine());
cr.setPoints(Integer.parseInt(in.readLine()));
ship.setId(in.readLine());
ship.setShipStatus(getShipStatus(in.readLine()));
ship.setPurpose(in.readLine());
wu[i] = new WorkUnit(ship,cr);
print(wu[i].toString());
}
} finally {
in.close();
}
} catch (Exception ex) { ex.printStackTrace(); }
for(int i = 0; i < wu.length;i++) {
print(wu[i].toString());
}
}
这是输出
16
2
WorkUnit{ship=Ship{id='F010', purpose='Programming and Computer Support', shipStatus=on_task}, crew=Crew{id='JK001', name='Obe Two Canobi', experiencePoints=125, status=false, classification=Specialised}, available=true}
WorkUnit{ship=Ship{id='F010', purpose='Programming and Computer Support', shipStatus=on_task}, crew=Crew{id='JK001', name='Obe Two Canobi', experiencePoints=125, status=false, classification=Specialised}, available=true}
Exception in thread "main" java.lang.NullPointerException
at SpaceCity.loadFile(SpaceCity.java:131)
at SpaceCity.addMenuChoice(SpaceCity.java:81)
at SpaceCity.MainMenu(SpaceCity.java:32)
at SpaceCity.main(SpaceCity.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Process finished with exit code 1
答案 0 :(得分:1)
列表wu有2个空格,但我跳了8个。改变代码
for(int i=0;i<length/8;i+=8) {
到
for(int i=0;i<length/8;i++) {