Skip to content

Instantly share code, notes, and snippets.

@theArjun
Created January 18, 2019 10:32
Show Gist options
  • Select an option

  • Save theArjun/403cb9dbd5b36b108b80f77c67c67a57 to your computer and use it in GitHub Desktop.

Select an option

Save theArjun/403cb9dbd5b36b108b80f77c67c67a57 to your computer and use it in GitHub Desktop.
Merge Two Text Files Sequentially and Alternatively
// This merges the two text files named "abc.txt" and "xyz.txt" alternatively.
// This question was asked later in Java Class 18 January, 2019.
import java.io.*;
class MergeFiles{
public static void main(String[] args)throws IOException{
try{
PrintWriter pw = new PrintWriter(new File("finalText.txt"));
BufferedReader brOne = new BufferedReader(new FileReader("abc.txt"));
BufferedReader brTwo = new BufferedReader(new FileReader("xyz.txt"));
String lineOne = brOne.readLine();
String lineTwo = brTwo.readLine();
while (lineOne != null || lineTwo != null) { // Denotes no character
pw.write(lineOne+"\n");
pw.write(lineTwo+"\n");
lineOne = brOne.readLine(); // Iteratively reads the line one by one until loop terminates.
lineTwo = brTwo.readLine();
}
pw.flush();
pw.close();
brOne.close();
brTwo.close();
}catch(IOException error){
error.printStackTrace();
}
}
}
// This merges the two text files named "abc.txt" and "xyz.txt" sequentially.
// This question was asked at first in Java Class 18 January, 2019.
import java.io.*;
class MergeFiles{
public static void main(String[] args)throws IOException{
try{
PrintWriter pw = new PrintWriter(new File("finalText.txt"));
BufferedReader br = new BufferedReader(new FileReader("abc.txt"));
String line = br.readLine();
while (line != null ) { // Denotes no character
pw.write(line+"\n");
line = br.readLine(); // Iteratively reads the line one by one until loop terminates.
}
br = new BufferedReader(new FileReader("xyz.txt"));
line = br.readLine();
while (line != null) { // Denotes no character
pw.write(line + "\n");
line = br.readLine(); // Iteratively reads the line one by one until loop terminates.
}
pw.flush();
pw.close();
br.close();
}catch(IOException error){
error.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment