将文件文本传递到hashmap

时间:2017-11-19 07:57:43

标签: java hashmap jfilechooser

我有一些问题试图传递我的程序读取的文件并按顺序排序。我不习惯使用文件,而且我没有考虑如何实现这一目标。

///////////////////////////////////////上课文件///// //////////////////////////////

import java.io. *; 公共类InFileReader {

private BufferedReader inputStream = null;

private String fileLine;

私有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 {

这就是事情刚刚崩溃的地方:

String input = fileReader.getFile(fileRead.getAbsoluteFile());

我的目的是传递文件的位置,以便getFile类可以读取它,然后将其排序到hashmap中。 再次,我不熟悉如何使用文件,任何建议或评论将不胜感激。 先谢谢你。

1 个答案:

答案 0 :(得分:0)

如果您收到FileNotFoundException,则找不到该文件。 你说文件名是“C:\ Users \ abe \ IdeaProjects \ CreateSeaPortDataFile \ src \ text.txt”。 如果在代码中键入该名称,则必须使用反斜杠:

"C:\\Users\\abe\\IdeaProjects\\CreateSeaPortDataFile\\src\\text.txt".