java - 使用 java 在 (.txt) 文件中的特定行号处插入文本

标签 java

 public void urlWriter(int y) throws IOException
            {
           File file = new File("C:\\DRIVE\\datas.txt");
           FileWriter fw = new FileWriter(file);
           BufferedReader dummyReader = new BufferedReader(new FileReader(file));

           BufferedWriter latestSource = new BufferedWriter(fw);


          //dummy string to read line by line
          String dooms =null;


         //loop for reading line by line
            for(i=0;i<y;i++) 
            {   
            while ((dooms=dummyReader.readLine())!=null)
            {


               //y line
                latestSource.write(CommonData.entered_direct);
                latestSource.newLine();
                //y+1 line
                latestSource.write(CommonData.entered_cellar);
                latestSource.newLine();
                //y+2 line
                latestSource.write(CommonData.entered_tele);
                latestSource.close();

            }
            }

尝试逐行读取,然后在特定位置写入。但同样的问题存在..有人可以帮助我吗...???

场景:如果 y 值作为“4”传递,则文本文件中的第 4、5、6 行应替换为新数据。如果有人帮助我,将非常感激。预先感谢!

面临的问题:所有数据都写入文本文件的底部,而不是坚持指定的行号

最佳答案

你想要的可能只能通过逐行读取文件然后才能实现

  • 如果新文本是要替换的行之一,请写入新文本。
  • 否则,请编写原始行。

然后您将拥有原始文件和新文件。您可以相应地重命名它们,这样您还可以备份上次更改。

粗略轮廓:

 open input file (i.e. BufferedReader)
 open new outfile file (i.e. some Writer)
 line = 0
 data = read line from input
 while (there is data) 
    line = line + 1
    if (line >= y && line <= y+2)
        write replaced data
    else
        write data
    data = read line from input
close output file
close input file

关于java - 使用 java 在 (.txt) 文件中的特定行号处插入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21110943/

相关文章:

java - 在后台运行 Activity

java - 使用 Spring MVC 和 Hibernate 进行 Ajax 调用

java - 如何在 ArrayList 中添加 10 个特定产品(对象),每个产品(对象)具有不同的数据类型?

java - 连接到 Kerberrized HDFS,java.lang.IllegalArgumentException : Failed to specify server's Kerberos principal name;

c# - 不使用 IP 识别机器

java - 货币代码到货币符号映射

Java Swing - 使用 Swing Timer 类移动 JLabels

java - Android:将大图像从 url 传递到 ImageView

java - 如何折叠搜索结果中的重复项

java - 在 java 中处理目录和数据