更改文件中的 ID

Change ID in File

假设我有这个记事本文件 姓名: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 为真,在这种情况下您存储 line.replace("1568","0003)(字符串由 replace 调用返回)。 然后关闭你的 reader,打开一个 BufferedWriter,并以相同的顺序写回行,不要忘记在每行之间调用 newLine()。瞧!