使用java程序编辑文本文件中的特定行

2024-01-06

好吧,假设我有一个名为“people.txt”的文本文件,它包含以下信息:

 1 adam 20 M
 2 betty 49 F
 3 charles 9 M
 4 david 22 M
 5 ethan 41 M
 6 faith 23 F
 7 greg 22 M
 8 heidi 63 F

基本上,第一个数字是该人的 ID,然后是该人的姓名、年龄和性别。假设我想用不同的值替换第 2 行,或者 ID 号为 2 的人。现在,我知道我不能使用RandomAccessFile这是因为名称和年龄的字节数并不总是相同。在随机搜索 Java 论坛时,我发现StringBuilder or StringBuffer应该足以满足我的需求,但我不知道如何实现。它们可以用来直接写入文本文件吗?我希望它可以直接根据用户输入工作。


刚刚为您创建了一个示例

public static void main(String args[]) {
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream("d:/new6.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine;
            StringBuilder fileContent = new StringBuilder();
            //Read File Line By Line
            while ((strLine = br.readLine()) != null) {
                // Print the content on the console
                System.out.println(strLine);
                String tokens[] = strLine.split(" ");
                if (tokens.length > 0) {
                    // Here tokens[0] will have value of ID
                    if (tokens[0].equals("2")) {
                        tokens[1] = "betty-updated";
                        tokens[2] = "499";
                        String newLine = tokens[0] + " " + tokens[1] + " " + tokens[2] + " " + tokens[3];
                        fileContent.append(newLine);
                        fileContent.append("\n");
                    } else {
                        // update content as it is
                        fileContent.append(strLine);
                        fileContent.append("\n");
                    }
                }
            }
            // Now fileContent will have updated content , which you can override into file
            FileWriter fstreamWrite = new FileWriter("d:/new6.txt");
            BufferedWriter out = new BufferedWriter(fstreamWrite);
            out.write(fileContent.toString());
            out.close();
            //Close the input stream
            in.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用java程序编辑文本文件中的特定行 的相关文章

随机推荐