简体   繁体   English

如何将txt文件放置到第二个txt文件的特定行

[英]how to put txt file to specific line of the second txt file

I have 2 files, one is new.txt and second is template.txt i need to put new.txt to the 6 line of template.txt and don't understand how to do that. 我有2个文件,一个是new.txt,第二个是template.txt,我需要将new.txt放到template.txt的6行中,但不知道该怎么做。 let's show you what i already have! 让我们向您展示我已经拥有的!

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        File dir = new File(".");

        String source = dir.getCanonicalPath() + File.separator + "new.txt";
        String dest = dir.getCanonicalPath() + File.separator + "template.txt";

        File fin = new File(source);
        FileInputStream fis = new FileInputStream(fin);
        BufferedReader in = new BufferedReader(new InputStreamReader(fis));

        FileWriter fstream = new FileWriter(dest,true);
        BufferedWriter out = new BufferedWriter(fstream);

        String aLine = null;
        while((aLine = in.readLine()) != null){
            out.write(aLine);
            out.newLine();
        }
        in.close();
        out.close();
    }
}

Files don't have an "insert" operation. 文件没有“插入”操作。 You can't simply write something to the middle of the file. 您不能简单地在文件中间写入内容。 Writes happen at a given offset, and they override whatever is already there. 写操作以给定的偏移量发生,并且它们会覆盖已存在的所有内容。

So you need to create a temp file, copy lines 1-5 of new.txt into it. 因此,您需要创建一个临时文件,将new.txt 1-5行复制到其中。 Then write line 6 from the template, followed by the rest of new.txt . 然后从模板中编写第6行,然后是其余的new.txt Once you're done, delete new.txt and rename the temp file to new.txt . 完成后,删除new.txt并将临时文件重命名为new.txt

If the files a are guaranteed to be small, you can replace the temp file with an in-memory buffer. 如果保证文件a较小,则可以用内存缓冲区替换临时文件。

Pseudo code to comment above: 上面要注释的伪代码:

File fileOne = new File("new.txt");
File fileTwo = new File("template.txt");

List<String> listOne = new ArrayList<String>();
List<String> listTwo = new ArrayList<String>();

String s = "";

while((s = fileOne.readLine()) != null){
  listOne.add(s);
}

for(int i = 0; i < listOne.size(); i++){
  if(i == 5){
    String s2 = "";
    while((s2 = fileTwo.readLine()) != null){
      listTwo.add(s);
    }
  }
  listTwo.add(listOne.get(i));
}

Like I said this is only pseudo code, so may not work, but that will be good exercise for you to make it work. 就像我说的那样,这只是伪代码,因此可能不起作用,但这对您来说是个好习惯。 I hope you understand the idea behind it. 我希望您了解其背后的想法。

PS. PS。 of course after you do that, you have to write all data from listTwo to file which you want. 当然,这样做之后,您必须将listTwo所有数据写入listTwo的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM