簡體   English   中英

如何將txt文件放置到第二個txt文件的特定行

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

我有2個文件,一個是new.txt,第二個是template.txt,我需要將new.txt放到template.txt的6行中,但不知道該怎么做。 讓我們向您展示我已經擁有的!

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();
    }
}

文件沒有“插入”操作。 您不能簡單地在文件中間寫入內容。 寫操作以給定的偏移量發生,並且它們會覆蓋已存在的所有內容。

因此,您需要創建一個臨時文件,將new.txt 1-5行復制到其中。 然后從模板中編寫第6行,然后是其余的new.txt 完成后,刪除new.txt並將臨時文件重命名為new.txt

如果保證文件a較小,則可以用內存緩沖區替換臨時文件。

上面要注釋的偽代碼:

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));
}

就像我說的那樣,這只是偽代碼,因此可能不起作用,但這對您來說是個好習慣。 我希望您了解其背后的想法。

PS。 當然,這樣做之后,您必須將listTwo所有數據寫入listTwo的文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM