Created
January 18, 2019 10:32
-
-
Save theArjun/403cb9dbd5b36b108b80f77c67c67a57 to your computer and use it in GitHub Desktop.
Merge Two Text Files Sequentially and Alternatively
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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