如何用java中的其他字符串替换文件中的字符串

时间:2015-06-19 00:17:06

标签: java string file replace

我有一个文件,每行包含这样的字符串:

usual,proper,complete,1,convenient,convenient,nonprob,recommended,recommend

我想用这样的代码替换每个单词:

1000, 100, 110, 110, 111, 001, 111, 111, 1000

以下是我使用的代码,但仍然不完整:

public class Codage {
    BufferedReader in;

    public Codage() {
        try {
            in = new BufferedReader(new FileReader("nursery.txt"));
            FileOutputStream fos2 = new FileOutputStream("nursery.txt");
            DataOutputStream output = new DataOutputStream(fos2);
            String str;

            while (null != ((str = in.readLine()))) {

                String delims = ",";
                String[] tokens = str.split(delims);
                int tokenCount = tokens.length;
                for (int j = 0; j < tokenCount; j++) {
                    if (tokens[j].equals("usual")) {
                        tokens[j] = "1000";
                        output.writeChars(tokens[j]);

                    }
                    //continue the other cases
                }
                System.out.print(str);
            }

            in.close();

        } catch (IOException e) {

            System.out.println("There was a problem:" + e);
        }
    }

    public static void main(String[] args) {
        Codage c = new Codage();
    }

}

我的代码错误地替换了值。

1 个答案:

答案 0 :(得分:3)

首先,您在此处编写的代码无效,因为当您打开outputStream到您尝试读取的确切文件时,它将清空源文件,语句in.readLine()始终返回null。所以,如果这是你真正的代码,也许这就是问题所在。

我认为您应该知道您应该将要打开的文件和要写入的文件分开。也就是说,当您打开要读取的nursery.txt时,您应该在同一路径中创建一个名为nursery.tmp的临时文件的outputStream,并且在该过程完成后,您可以删除nursery.txt并重命名该托儿所.tmp到nursery.txt。

如果我是你,我也不会使用if-else结构来完成工作。它接缝你有独特的键,如:

通常,正确,完整,方便,方便,非推荐,推荐,推荐

因此,使用地图结构查找替换值可能更方便:

通常,正确,完整,方便,方便,非推荐,推荐,推荐,......

1000,100,110,110,111,001,111,111,......

但这些只是一些猜测,你知道如何管理你的业务逻辑。

在那部分之后,我认为将输出数据创建为String行并将它们逐行写入nursery.tmp是一个更好的主意:

public class Codage {

    private BufferedReader in;
    private BufferedWriter out;

    private HashMap<String, String> replacingValuesByKeys = new HashMap<String, String>();

    public Codage() {
        initialize();
    }

    private void initialize() {
        // I assumed that you have rule that a key like "proper" always goes to "100"
        // Initialize the map between keys and replacing values: 
        replacingValuesByKeys.put("usual", "1000");
        replacingValuesByKeys.put("proper", "100");
        replacingValuesByKeys.put("complete", "110");
        replacingValuesByKeys.put("convenient", "110");
        replacingValuesByKeys.put("nonprob", "111");
        replacingValuesByKeys.put("recommended", "001");
        replacingValuesByKeys.put("recommend", "1000");
    }

    public void doRelpacementInFile(){
        try {
            in = new BufferedReader(new FileReader("c:/nursery.txt"));
            out = new BufferedWriter(new FileWriter("c:/nursery.tmp"));

            String str = in.readLine();
            while (null != str) {
                Iterator<String> it = replacingValuesByKeys.keySet().iterator();
                while(it.hasNext())
                {
                    String toBeReplaced = it.next();
                    String replacementValue = replacingValuesByKeys.get(toBeReplaced);
                    // \\b is for word boundary, because you have both recommend and recommended
                    //        and we do not want to replacing the [recommend] part of recommended.
                    str = str.replaceAll("\\b"+toBeReplaced+"\\b", replacementValue);
                }
                // Write the fully replaced line to the temp file:
                out.append(str);
                out.newLine();

                // Do not forget to read the next line:
                str = in.readLine();
            }

        } catch (IOException e) {
            System.out.println("There was a problem:" + e);
        } finally{
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        File f = new File("c:/nursery.txt");
        f.delete();

        File f2 = new File("c:/nursery.tmp");
        f2.renameTo(new File("c:/nursery.txt"));
    }


    public static void main(String[] args) {
        Codage c = new Codage();
        c.doRelpacementInFile();
    }

}

希望这些片段有用,

祝你好运。