简体   繁体   中英

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. 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. Then write line 6 from the template, followed by the rest of new.txt . Once you're done, delete new.txt and rename the temp file to new.txt .

If the files a are guaranteed to be small, you can replace the temp file with an in-memory buffer.

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. of course after you do that, you have to write all data from listTwo to file which you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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