Advertisement
brilliant_moves

FileMerger.java

Sep 13th, 2017
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.35 KB | None | 0 0
  1. import java.io.BufferedWriter;
  2. import java.io.FileWriter;
  3. import java.io.File;
  4. import java.io.Writer;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7.  
  8. public class FileMerger {
  9.     /* By Chris Clarke, 13.09.2017 */
  10.  
  11.     public void writeFile(String filename, String text) {
  12.         Writer writer = null;
  13.         try {
  14.             File file = new File(filename);
  15.             writer = new BufferedWriter(new FileWriter(file));
  16.             writer.write(text);
  17.         } catch (FileNotFoundException e) {
  18.             e.printStackTrace();
  19.         } catch (IOException e) {
  20.             e.printStackTrace();
  21.         } finally {
  22.             try {
  23.                 if (writer != null) {
  24.                     writer.close();
  25.                 }
  26.             } catch (IOException e) {
  27.                 e.printStackTrace();
  28.             }
  29.         }
  30.     }
  31.  
  32.     public void alternate(String fname, String t1, String t2) {
  33.         String[] text1 = t1.split("\r\n");
  34.         String[] text2 = t2.split("\r\n");
  35.         String result = "";
  36.         for (int i=0;i<text1.length; i++) {
  37.             result += text1[i] + "\r\n";
  38.             if (i<text2.length) result += text2[i]+"\r\n";
  39.         }
  40.         writeFile(fname, result);
  41.     }
  42.  
  43.     public static void main(String[] args) {
  44.         FileMerger fm = new FileMerger();
  45.         String text1 = "Hello\r\nHow are you?\r\nBye";
  46.         fm.writeFile("File1.dat", text1);
  47.         String text2 = "Welcome to the Computer Lab\r\nThere are 2 Labs in the Senior School";
  48.         fm.writeFile("File2.dat", text2);
  49.         fm.alternate("File3.dat", text1, text2);
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement