假设我有这个记事本文件
名称:Company_XXX_768_JGH.txt
内容:

Random Text

Blah Blah Blah

Network ID: 80801568


我需要将ID的最后4个数字(1568)更改为(0003)。

到目前为止,我已经可以阅读全文,找到带有数字的行并为该行打印一条语句。现在,我需要用新的数字替换最后的4个数字。

到目前为止,我得到了:

-------------------------------在JP回答后---------------- --------------

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class test {
    public static void main(String [] args) throws IOException {

        File TEMP = new File("C:\\Users\\Controlled\\Documents\\Company\\E_20150512_101105_0002_80802221_SSH.xml");
        boolean fileExists = TEMP.exists();
        System.out.println(fileExists);
        // The name of the file to open.

        // This will reference one line at a time
        String line = null;

        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader =
                new FileReader(TEMP);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader =
                new BufferedReader(fileReader);
            List<String> NewTextFile = new ArrayList<String>();

            while((line = bufferedReader.readLine()) != null) {
                //System.out.println(line);
                boolean containsSSH = line.contains("80802221");
                if (containsSSH == true)
                {
                String correctedLine = line.replace("2221","0003");
                    NewTextFile.add(correctedLine);
                    System.out.println(correctedLine);
                }
                else
                {
                    NewTextFile.add(line);
                }

            }
            bufferedReader.close();
            // Always close files.
            File file = new File("C:\\Users\\Controlled\\Documents\\Company\\Test.xml");
            FileWriter fw = new FileWriter(file.getAbsoluteFile());

            // if file doesn't exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            BufferedWriter bw = new BufferedWriter (fw);
            bw.write(line); // How to write a List to a file?
            bw.close();

        }
        catch(FileNotFoundException ex) {
            System.out.println(
                "Unable to open file '" +
                TEMP + "'");
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file '"
                + TEMP + "'");
            // Or we could just do this:
            // ex.printStackTrace();
        }
    }
}

最佳答案

将您阅读的每一行存储在一个列表中(无关紧要的是ArrayList或LinkedList)。按原样存储该行,除非containsSSH为true,否则存储line.replace("1568","0003)(该字符串由replace调用返回)。
然后关闭您的阅读器,打开BufferedWriter,并以相同的顺序写回各行,不要忘记在每行之间调用newLine()。瞧!

09-26 11:07