簡體   English   中英

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

[英]how to replace strings in a file by other strings in java

我有一個文件,每行包含這樣的字符串:

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();
    }

}

我的代碼錯誤地替換了值。

首先,您在此處編寫的代碼不起作用,因為當您打開outputStream到您嘗試讀取的確切文件時,它將清空源文件並且語句in.readLine()始終返回null。 所以,如果這是你真正的代碼,也許這就是問題所在。

我假設您知道您應該將要打開的文件和要寫入的文件分開。 也就是說,當您打開要讀取的nursery.txt時,您應該在同一路徑中創建一個名為nursery.tmp的臨時文件的outputStream,並且在該過程完成后,您可以刪除nursery.txt並重命名該托兒所.tmp到nursery.txt。

如果我是你,我也不會使用if-else結構來完成工作。 它接縫你有獨特的鍵,如:

通常,正確,完整,方便,方便,nonprob,推薦,推薦

因此,使用地圖結構查找替換值可能更方便:

通常,正確,完整,方便,方便,nonprob,推薦,推薦,...

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();
    }

}

希望這些片段有用,

祝好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM