Java从HashMap中删除并在文件中写入更改

时间:2014-09-07 21:22:48

标签: java for-loop file-io hashmap

所以这里我有代码我有HashMap由文件中的单词组成,我正在添加单词并将它们写在文件上并且它可以正常工作,但是当我使用我的删除函数进行一些reaseon时,这里没有做任何事情是代码:

  import java.io.BufferedWriter;
  import java.io.File;
  import java.io.FileNotFoundException;
  import java.io.FileWriter;
  import java.util.HashMap;
  import java.util.Map;
   import java.util.Scanner;

   public class Main {
   public static File file = new File( C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt");
public static int value = 1;
private static Scanner input;
public static Scanner in = new Scanner(System.in);
public static Map<String, Integer> map = new HashMap<String, Integer>();

public static void main(String[] args) throws FileNotFoundException {
    readFile();
    System.out.println("Enter number of function wanted" + "\n1 to add"
            + "\n2 for searching by prefix" + "\n3 for deleting");
    int choice = in.nextInt();
    if (choice == 1) {
        System.out.println("enter words seprated by comma");
        String wd = in.next();
        add(wd);
    }
    if (choice == 2) {
        System.out.println("Enter prefix");
        String wd = in.next();
        prefixSearch(wd);
    }
    if (choice == 3) {
        System.out.println("ENTER word to delete");
        String wd = in.next();
        remove(wd);
    }

}

public static void readFile() throws FileNotFoundException {
    input = new Scanner(file);
    boolean done = false;

    int value = 1;

    while (input.hasNext()) {
        String word = input.next().toLowerCase();
        String[] line = word.split("[,\\s]+");
        for (int j = 0; j < line.length; j++) {
            map.put(line[j], value);
            value++;
            done = true;
        }
    }
    if (done == true) {
        System.out.println("Succes");
    }
}

public static void prefixSearch(String wd) {
    System.out.println("Enter prefix");
    String prefix = wd.toLowerCase();
    for (Map.Entry<String, Integer> key : map.entrySet()) {
        if (key.getKey().startsWith(prefix)) {
            System.out.println(key.getKey());
        }
    }

}

public static void add(String wd) {
    boolean done = false;
    String word = wd.toLowerCase();
    String[] line = word.split("[,\\s]+");
    for (int j = 0; j < line.length; j++) {
        if (!map.containsKey(line[j])) {
            map.put(line[j], value);
            value++;

            try {
                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(map.toString());
                bw.close();
                done = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            continue;
        }
    }

    if (done == true) {
        System.out.println("Success");
    }

}

public static void remove(String wd) {
    boolean done = false;
    String word = wd.toLowerCase();
    String[] line = word.split("[,\\s]+");
    for (int j = 0; j < line.length; j++) {
        for (Map.Entry<String, Integer> key : map.entrySet()) {
            if (key.getKey().equals(line[j])) {
                map.remove(key.getKey(), key.getValue());
                try {
                    FileWriter fw = new FileWriter(file.getAbsoluteFile());
                    BufferedWriter bw = new BufferedWriter(fw);
                    bw.write(map.toString());
                    bw.close();
                    done = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                continue;
            }
        }

    }
    if (done == true) {
        System.out.println("Succes");
    }

}

}

其他每种方法都运行正常,但请删除。循环是否有问题,可能使用更优化的方式或?

2 个答案:

答案 0 :(得分:0)

我在代码中可以看到的问题如下:

  1. 在定义文件时忘记了引用:

    public static File file = new File( C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt")

  2. 应该是:

    public static File file = new File("C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt");
    
    1. 地图中的remove()函数只接收一个参数,这是您要删除的条目的键,因此:

      map.remove(key.getKey(), key.getValue());

    2. 应该是:

      map.remove(key.getKey());
      

      此外,由于您获取了地图的entrySet,因此您可以考虑将rename()函数中的key变量重命名为entry

答案 1 :(得分:0)

失败的原因是您在迭代条目时尝试更改地图。与任何集合一样 - 如果您在迭代时尝试修改它,您将获得ConcurrentModificationException

此外,还有一个冗余的内部for循环(冗余,因为地图的整个目的是当你正在寻找一个特定的值时,你不必迭代它)这意味着当只有一次足够时,你会尝试多次覆盖该文件。

public static void remove(String wd) {
    boolean done = false;
    String word = wd.toLowerCase();
    String[] line = word.split("[,\\s]+");
    for (int j = 0; j < line.length; j++) {
        map.remove(line[j]);
    }
    try {
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(map.toString());
        bw.close();
        done = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (done == true) {
        System.out.println("Success");
    }
}