【发布时间】:2018-05-02 15:43:16
【问题描述】:
我在尝试传递由我的程序读取并进行相应排序的文件时遇到了一些问题。我不习惯使用文件,而且我对如何实现这一点没有任何想法。
////////////////////////////////类读取文件///// //////////////////////////
导入 java.io.*; 公共类 InFileReader {
private BufferedReader inputStream = null;
私有字符串文件行;
private StringBuilder sb;
public String getFile(File fileRead) 抛出 FileNotFoundException, IOException {
inputStream = new BufferedReader(new FileReader(fileRead)); //reads files
sb = new StringBuilder();
while((fileLine = inputStream.readLine()) != null){//keep reading lines in file till there is none
sb.append(fileLine).append("\n");
}
return sb.toString(); //returns StringBuffer read values in String form
} } ///////////////////////////////////////// /// 读取文件类结束 ////////////////////
public void getFile(File fileRead) 抛出 FileNotFoundException,
IOException {
try {
String input = fileReader.getFile(fileRead.getAbsoluteFile());
HashMap<Integer, Thing.Ship> hashmap = new HashMap<>();
while (!input.isEmpty()) { // as long as there is data in the file keep looping
Scanner sc = new Scanner(input); // scan file
if (!input.startsWith("//")) { // take out "//" from directory
String type = "";
if (sc.hasNext()) { // if there are character lines get next line
type = sc.next();
}
if (type.equalsIgnoreCase("port")) { // looks for "port"
world.assignPort(new Thing.SeaPort(sc)); // assigns value to Seaport
} else if (type.equalsIgnoreCase("dock")) {
world.assignDock(new Thing.Dock(sc));
} else if (type.equalsIgnoreCase("ship")) {
Thing.Ship s = new Thing.Ship(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("pship")) {
Thing.Ship s = new Thing.PassengerShip(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("cship")) {
Thing.Ship s = new Thing.CargoShip(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("person")) {
world.assignPerson(new Thing.Person(sc));
}
}
}
//inputOut.setText(type);
inputOut.setText(world.toString());
} catch (Exception e) {
System.out.println(e + "-----");
}
}
这里 fileRead 知道在哪里可以找到要读取的文件 "C:\Users\abe\IdeaProjects\CreateSeaPortDataFile\src\text.txt"
public void getFile(File fileRead) 抛出 FileNotFoundException,
IOException {
这就是事情崩溃的地方:
字符串输入 = fileReader.getFile(fileRead.getAbsoluteFile());
我在这里的意图是传递文件的位置,以便 getFile 类可以读取它,然后将其分类到 hashmap 中。 再次,我不熟悉如何使用文件,任何建议或评论将不胜感激。 谢谢你。
【问题讨论】:
标签: java hashmap jfilechooser