File merging in java

Java Program to merge two files in a third file

In this tutorial, we are going to learn how to merge two files using Java Program.

To merge the two files into the third file firstly, we need to create two files namely f1 and f2.
We should create the files f1 and f2 in the same folder.

Merge two files in Java

Let us assume that the contents of files as:
file1 contains: hello all !!

file2 contains: learn programming from codespeedy .
After merging the two files the file3 contains: hello all !! learn programming from codespeedy.

import java.io.*; import java.util.Scanner; public class MergeProgram < public static void main(String args[]) < String file1, file2, file3; Scanner scan = new Scanner(System.in); System.out.print("Enter file1 : "); file1 = scan.nextLine(); System.out.print("Enter file2 : "); first2 = scan.nextLine(); System.out.print("Enter the third file : "); file3 = scan.nextLine(); File[] files = new File[2]; files[0] = new File(file1); files[1] = new File(file2); File mergedF3 = new File(file3); mergeFiles(files, mergedF3); >public static void mergeFiles(File[] files, File mergedF3) < FileWriter fstream = null; BufferedWriter out = null; try < fstream = new FileWriter(mergedF3, true); out = new BufferedWriter(fstream); >catch(IOException e) < e.printStackTrace(); >for(File f : files) < FileInputStream fis; try < fis = new FileInputStream(f); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String aLine; while((aLine = in.readLine()) != null) < out.write(aLine); out.newLine(); >in.close(); > catch(IOException e1) < e1.printStackTrace(); >> System.out.print("\nTwo files are succesfully merged into the third file."); try < out.close(); >catch(IOException e1) < e1.printStackTrace(); >> >

The above code will give the following output.
Assume that file1 contains “hello all!!”.
File2 contains “learn programming from codespeedy.” after merging the file1 and file2 into file3.
The code gives the output as “two files are successfully merged into the third file.”
When we open the file3 it contains”hello all!! learn programming from codespeedy.”

Enter file1: file1.txt Enter file2: file2.txt Enter the third file: file3 Two files are successfully merged into the third file.

Источник

Читайте также:  Change background on scroll css

Merging files Using Java

In case of a conflict while copying files, where the same filename exists in multiple folders, the preference is to copy the file with the most recent timestamp to the mergedFolder. For instance, consider file1 and file2 merged together in the output. The solution involves an algorithm to merge adjacent files, which includes reading the lines from the two files into two separate lists.

Merging files Using Java

I possess a pair of documents, namely arrivals.txt and pickups.txt.

TickeNum,Loc,DayofMonth,Hour 1421,127,12,8 1422,108,12,8 1423,110,12,9 1424,112,12,9 1425,101,12,9 1426,105,12,9 1427,106,12,10 1428,109,12,10 1429,102,12,11 1430,107,12,12 1431,122,12,14 1432,128,12,17 1433,132,12,19 1434,136,12,21 1435,141,12,23 1436,142,13,6 
TickeNum,DayofMonth,Hour 1422,12,9 1428,12,12 1423,12,13 1429,12,14 1431,12,16 1424,12,17 1421,12,18 1425,12,19 1426,13,21 1434,13,7 1435,13,9 1436,13,16 1430,13,19 1432,13,20 
Ticket: 1422, Arrived: 12: 8 --- Pickup: 12: 9 ------ Cost: 7.00 Ticket: 1428, Arrived: 12:10 --- Pickup: 12:12 ------ Cost: 10.00 Ticket: 1423, Arrived: 12: 9 --- Pickup: 12:13 ------ Cost: 15.00 Ticket: 1429, Arrived: 12:11 --- Pickup: 12:14 ------ Cost: 13.00 Ticket: 1431, Arrived: 12:14 --- Pickup: 12:16 ------ Cost: 10.00 Ticket: 1424, Arrived: 12: 9 --- Pickup: 12:17 ------ Cost: 22.00 Ticket: 1421, Arrived: 12: 8 --- Pickup: 12:18 ------ Cost: 22.00 Ticket: 1425, Arrived: 12: 9 --- Pickup: 12:19 ------ Cost: 22.00 Ticket: 1426, Arrived: 12: 9 --- Pickup: 13:21 ------ Cost: 52.00 Ticket: 1434, Arrived: 12:21 --- Pickup: 13: 7 ------ Cost: 35.00 Ticket: 1435, Arrived: 12:23 --- Pickup: 13: 9 ------ Cost: 29.00 Ticket: 1436, Arrived: 13: 6 --- Pickup: 13:16 ------ Cost: 22.00 Ticket: 1430, Arrived: 12:12 --- Pickup: 13:19 ------ Cost: 52.00 Ticket: 1432, Arrived: 12:17 --- Pickup: 13:20 ------ Cost: 48.00 

Here’s my code up until now, which you will likely require.

I possess a merge method in a separate file.

public static void merge(File file1, File file2) throws IOException < Scanner scanner1 = new Scanner(file1); Scanner scanner2 = new Scanner(file2); while (scanner1.hasNextLine() && scanner2.hasNextLine()) < String trash = scanner1.nextLine(); String trash2 = scanner2.nextLine(); String line1 = scanner1.nextLine(); String line2 = scanner2.nextLine(); // parse line1 String[] line1Tokens = line1.split(","); // parse line2 String[] line2Tokens = line2.split(","); // Print String ticket = line1Tokens[0]; String arrived1 = line1Tokens[2]; String arrived2 = line1Tokens[3]; String pickup1 = line2Tokens[1]; String pickup2 = line2Tokens[2]; System.out.println("Ticket: " + ticket + ", " + "Arrived: " + arrived1 + ":" + arrived2 + " --- " + "Pickup: " + pickup1 + ":" + pickup2 + " --- " + "Cost: "); >
Ticket: 1421, Arrived: 12:8 --- Pickup: 12:9 --- Cost: Ticket: 1423, Arrived: 12:9 --- Pickup: 12:13 --- Cost: Ticket: 1425, Arrived: 12:9 --- Pickup: 12:16 --- Cost: Ticket: 1427, Arrived: 12:10 --- Pickup: 12:18 --- Cost: Ticket: 1429, Arrived: 12:11 --- Pickup: 13:21 --- Cost: Ticket: 1431, Arrived: 12:14 --- Pickup: 13:9 --- Cost: Ticket: 1433, Arrived: 12:19 --- Pickup: 13:19 --- Cost: java.lang.ArrayIndexOutOfBoundsException: 1 at ParkingLot.merge(ParkingLot.java:65) at LotDriver.main(LotDriver.java:20) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272) 

A statement similar to this could suffice.

while (scanner1.hasNextLine() && (scanner2.hasNextLine()) < Strint line1 = scanner1.nextLine(); String line2 = scanner2.nextLine(); // parse line1 String[] line1Tokens = lineS1,split(","); // parse line2 String[] line2Tokens = line2.split(","); // Print String ticket = line1Tokens[0]; String arrived1 = line1Tokens[2]; String arraved2 = line1Tokens[3]; String pickup1 = line2Tokens[1]; String pickup2 = line2Tokens[2]; System.out.println("Ticket: " + ticket + ", " + "Arrived: " + arrived1 + ":" + arived2 + " --- " + "Pickup: " + pickup1 + ":" + pickup2 + " --- " + "Cost: "); >printWriter.close(); 

This presupposes that every line in the file corresponds correctly.

public static void merge(File file1, File file2) throws IOException < Scanner scanner1 = new Scanner(file1); Scanner scanner2 = new Scanner(file2); while (scanner1.hasNextLine() && (scanner2.hasNextLine())< Strint line1 = scanner1.nextLine(); String line2 = scanner2.nextLine(); // parse line1 String[] line1Tokens = lineS1,split(","); // parse line2 String[] line2Tokens = line2.split(","); // Print String ticket = line1Tokens[0]; String arrived1 = line1Tokens[2]; String arraved2 = line1Tokens[3]; String pickup1 = line2Tokens[1]; String pickup2 = line2Tokens[2]; System.out.println("Ticket: " + ticket + ", " + "Arrived: " + arrived1 + ":" + arived2 + " --- " + "Pickup: " + pickup1 + ":" + pickup2 + " --- " + "Cost: "); >> public static void main(String[] args)

To avoid printing the merge() method, simply return a String instead of using it.

Instead of printing, your method can return a String .

 public String merge(File file1, File file2) throws IOException < String entirePrint = ""; while (scanner1.hasNextLine() && (scanner2.hasNextLine())< // other code String oneLine = "Ticket: " + ticket + ", " + "Arrived: " + arrived1 + ":" + arived2 + " --- " + "Pickup: " + pickup1 + ":" + pickup2 + " --- " + "Cost: " + "/n"; entirePrint += oneLine; >return entirePrint; > 
 public static void main(String[] args)

To efficiently read both files, I suggest writing Java code that performs a single pass. Assuming familiarity with Java programming and merge sorts, combining these skills could be beneficial. However, a merge sort may not be necessary upon further consideration. Instead, data can be read in its original order and added to a data structure.

final Map map = new HashMap<>(); public MyRecord acquireRecord(int ticket) 

MyRecord stores all the details pertaining to a particular ticket number.

In case of any issue, start by utilizing a debugger. If you still face any difficulty, then share your existing code along with a precise query about it.

Merge Two XML Files in Java, I use XSLT to merge XML files. It allows me to adjust the merge operation to just slam the content together or to merge at an specific level. It is a little more work …

How to merge multiple files in Java?

Is it possible to combine several files into one? For instance, can I merge them?

Essentially, the process for merging files that are adjacent involves the following algorithm.

  1. Create two lists by reading the lines from both files.
  2. Combine the second list’s lines with the first list’s.
  3. Add any extra lines from the second list to the first list.
  4. Save the initial list in a file or any other location.

This is the way I executed the algorithm in Java 7.

import static java.nio.file.StandardOpenOption.*; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; import java.util.List; public class MergeFiles < public static void main(String[] args) throws IOException < // READ file1 into lines1 & file2 into lines2 final Charset CS = Charset.defaultCharset(); // e.g. UTF-8 Listlines1 = Files.readAllLines(Paths.get("file1"), CS), lines2 = Files.readAllLines(Paths.get("file2"), CS); // MERGE until end of either list, then APPEND until end of lines2 for (int i = 0; i < lines2.size(); i++) if (i < lines1.size()) lines1.set(i, lines1.get(i) + " " + lines2.get(i)); else lines1.add(lines2.get(i)); // WRITE lines1 (the merged lines) to some file3 Files.write(Paths.get("file3"), lines1, CS, CREATE, WRITE, TRUNCATE_EXISTING); >> 

Merge — Java: Merging 2 Zip files, Although it was just about appending single files, I thought I migh be able to use it to merge files. This is what I have right now: import …

How to merge two Folder files into one in Java

My goal is to develop a basic function that can either merge or duplicate multiple folder files into a solitary folder.

I began with the following and decided to share it here in hopes of receiving higher quality code.

public void copyDifferentFolderFilesIntoOne(String mergedFolderStr,String . foldersStr) < File mergedFolder= new File(mergedFolderStr); for(String folder: foldersStr) < //copy folder's files into mergedFolder >> 

In case of a conflict during file copying, where the same file name exists in multiple folders, I prefer to have the file with the most recent timestamp copied to the mergedFolder.

Are you aware of the most effective method for combining multiple folders or files into a single one?

Please inform me if the question is ambiguous or unclear.

By navigating through the merged directories and selecting the most recent files, you can generate a Map containing the files that need to be copied. Following that, you can proceed with copying the files from the directory to the designated location.

An example snippet of code, which I haven’t tested, could resemble the following.

public void copyDifferentFolderFilesIntoOne(String mergedFolderStr, String. foldersStr) < final File mergedFolder = new File(mergedFolderStr); final MapfilesMap = new HashMap (); for (String folder : foldersStr) < updateFilesMap(new File (folder), filesMap, null); >for (final Map.Entry fileEntry : filesMap.entrySet()) < final String relativeName = fileEntry.getKey(); final File srcFile = fileEntry.getValue(); FileUtils.copyFile (srcFile, new File (mergedFolder, relativeName)); >> private void updateFilesMap(final File baseFolder, final Map filesMap, final String relativeName) < for (final File file : baseFolder.listFiles()) < final String fileRelativeName = getFileRelativeName (relativeName, file.getName()); if (file.isDirectory()) < updateFilesMap(file, filesMap, fileRelativeName); >else < final File existingFile = filesMap.get (fileRelativeName); if (existingFile == null || file.lastModified() >existingFile.lastModified() ) < filesMap.put (fileRelativeName, file); >> > > private String getFileRelativeName(final String baseName, final String fileName) < return baseName == null ? fileName : baseName + "/" + fileName; >

Obtain the timestamp by referring to File.lastModified().

JAVA:Merge the multiple properties files, 1 Answer. Sorted by: -1. To make it work the way you want you should follow this to order: load common.properties merge test2.properties merge …

Источник

Merge Multiple File Types into One using Java

Merging different documents is often required when you intend to gather the scattered data of different documents into one single file. In this article, you will learn to automate the documents merging process. This will show how to programmatically merge multiple documents of either the same or different file types into one file using Java. In another post, we discussed merging multiple files of different formats using C#.

Merged PDF Word Excel Presentations to One PDF in Java

The following topics are covered below:

Java API for Merging Multiple Document Types#

I will be using GroupDocs.Merger for Java to combine documents of different file formats into one file. The Java API allows joining various documents of the same or different formats into one file. Furthermore, it allows documents to split, trim, swap, move, remove, rotate, or arrange pages accordingly. Additionally, it supports passwords and their removal to manage the security of the supported document formats.

Some of the document types the API supports include; word-processing documents, spreadsheets, presentations, HTML, PDF, eBooks, Visio drawings, CSV, and TSV.

Download and Configure#

Get the document merger library from the downloads section. For Maven-based Java applications, add the following configuration within pom.xml. Afterward, you can try document merging java examples of this article as well as many more from GitHub. For the details, you may also visit the API Reference.

 GroupDocsJavaAPI GroupDocs Java API http://repository.groupdocs.com/repo/  com.groupdocs groupdocs-merger 21.3  

Merge PDF, Word, Excel files into one PDF in Java#

PDF documents can be combined with your Word documents, Excel spreadsheets, PowerPoint presentations, and other PDF documents with just a few lines of code. The following are the steps of how to merge documents of multiple file types into one file.

  • Load the initial document using the Merger class.
  • Combine the second document using the join method.
  • Keep merging the other documents (if required) using the same or similar join method.
  • Save the final combined document on path or stream using the relevant save method.

The following source code shows how to merge PDF, Word, and Excel documents into one PDF file in Java.

Similarly, documents with the same file types can be combined. The below-mentioned is the output obtained by joining a word document, a PDF document. and a spreadsheet using the above-mentioned Java code.

Merge different file types into one PDF C#

Merge Selective Pages of Multiple PDF, Word, Excel files into One PDF in Java#

Merge selective page of different file types into one PDF C#

If you want to pick few pages from one document and some other selective pages from the next document, and so on. The API allows you to merge selective pages of multiple file types into one file in different ways.

  • Load the initial document using the Merger class.
  • Prepare the merging options with JoinOptions class.
  • Start merging the document using the join method.
  • Keep joining the documents by setting appropriate joining options for each document.
  • Save the final merged document using the save method.

The following source code shows how to merge the first page of a Word document and the even sheets of Excel spreadsheet in the provided range in Java with a PDF document. The output will be a single PDF file.

Get a Free API License#

You can get a free temporary license in order to use the API without the evaluation limitations.

Conclusion#

To conclude, you learned how to merge two or more documents of similar or different file types into one file using Java with your application. Additionally, you learned how to combine selective pages of multiple file types into one file.

You can learn more about GroupDocs.Merger using the documentation. In case you have queries, contact us via forum.

See Also#

Источник

Оцените статью