Reputation: 133
I would like to read multiple txt files and play an output file after the code interaction. how do I pass the files to the code? are three .txt files
import java.io.*;
import java.util.*;
public class Main1 {
public static void main(String[] args) throws IOException{
int n = Integer.parseInt(args[0]), i;
if(n <= 0) return;
String narq[] = new String[n];
for( i = 1 ; i <= n;i++)
narq[i - 1]= args[i];
Merge(n, narq, args[n + 1]);
}
static void Merge(int n, String [] narq, String exit1) throws
IOException{
BufferedReader in[] = new BufferedReader[n];
for(int i = 0; i < n; i++)
in[i] = new BufferedReader(new FileReader(narq[i]));
BufferedWriter out;
out = new BufferedWriter(new FileWriter(exit1));
}
}
Upvotes: 0
Views: 1094
Reputation: 9192
Rather than manipulating files you've put more work into manipulating the args[] String array. You don't really have to do this, instead utilize the fact that you have this variable. All you should have in your main() method is:
if (args.length == 0 || args.length < 2) {
return;
}
Merge(args);
and that's all, just pass the args[] String array to your merge() method which of course will need to be slightly modified. What do these code lines above do?
In the if statement the condition args.length == 0
is checked first and if true then this means that no Command Line arguments were passed to the application and therefore we exit the main() method with a return statement which ultimately
closes the application.
If however the first condition passes (there are Command Line arguments) then the || args.length < 2
condition is checked and if there were less than two arguments (file names) provided then again, we jump out of the main() method and exit the application. We need at least 2 file names to carry out any sort of file merge (a Source File Name and a Destination File Name). In your application the last argument within the Command Line is always to be considered the Destination File Path/Name. All other files listed within the Command Line will be merged into this file.
The last line is of course the call to the merge() method which does all the work. Because the call is from within the main() method the merge() method will need to be a static method and it might look something like this:
/**
* Merges supplied text files to a supplied single destination text file.<br><br>
*
* @param args (1D String Array) All elements (file paths) within the array are
* considered files to be merged to the destination file with the exception of
* the very last array element. This element must contain the destination file
* path itself. Two or more file paths must be provided within this array
* otherwise no merging takes place.<br>
*
* @param overwriteDestination (Optional - Boolean) Default is true whereas the
* merge destination file is always overwritten if it exists. If false is supplied
* then the destination file is not overwritten and merging files are appended to
* the existing data within that destination file.
*/
public static void merge(String[] args, boolean... overwriteDestination) {
boolean overwrite = true; // Default - Overwite Destination file if it exists.
if (overwriteDestination.length > 0) {
overwrite = overwriteDestination[0];
}
try ( // PrintWriter object for last file name in args array
PrintWriter pw = new PrintWriter(new FileWriter(args[args.length - 1], !overwrite))) {
// BufferedReader object for files in args array (except the last file).
BufferedReader br = null;
for (int i = 0; i < args.length - 1; i++) {
File f = new File(args[i]);
if (!f.exists() || f.isDirectory()) {
System.out.println("The specified file in Command Line named " +
args[i] + " does not appear to exist! Ignoring File!");
continue;
}
br = new BufferedReader(new FileReader(f));
String line;
/* Loop to copy each line of the file currrently
in args[i] to the last file provided in args
array (last file name in command line) */
while ((line = br.readLine()) != null) {
pw.println(line);
}
pw.flush();
// close reader;
br.close();
System.out.println("Merged " + args[i] + " into " + args[args.length - 1] + ".");
}
}
catch (FileNotFoundException ex) {
Logger.getLogger("merge() Method Error!").log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger("merge() Method Error!").log(Level.SEVERE, null, ex);
}
}
Modify the method to suit your needs if desired.
Upvotes: 4
Reputation: 2954
Recommend to use java.nio package. Here is the working code, update as required: Run with arguments such as - c:\a.txt c:\b.txt c:\c.txt
package stackoverflow;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import org.apache.commons.io.IOUtils;
public class Appender
{
private static String outFilePath = "c:\\merged.txt";
private static boolean needLineBreakAfterAppend = true;
public static void main(String[] args) throws IOException
{
if (args.length == 0) {
// handle
System.out.println("No input files provided, return without doing anything");
return;
}
Path destFilePathObj = Paths.get(outFilePath);
if (!Files.exists(destFilePathObj, LinkOption.NOFOLLOW_LINKS)) {
Files.createFile(destFilePathObj);
System.out.println("created destination file at " + outFilePath);
} else {
System.out.println("destination file at " + outFilePath + " was existing. Data will be appended");
}
Arrays.asList(args).forEach(filePathToAppend -> merge(filePathToAppend, destFilePathObj));
}
private static void merge(String filePathToAppend, Path destFilePathObj)
{
boolean fileExists = Files.exists(Paths.get(filePathToAppend));
if (fileExists) {
System.out.println("Input file was found at path " + filePathToAppend);
try {
// Appending The New Data To The Existing File
Files.write(destFilePathObj, IOUtils.toByteArray(new FileReader(filePathToAppend)),
StandardOpenOption.APPEND);
System.out.println("Done appending !");
if (needLineBreakAfterAppend) {
Files.write(destFilePathObj, "\n".getBytes(), StandardOpenOption.APPEND);
}
} catch (IOException ioExceptionObj) {
// handle it
}
} else {
System.out.println("Input file was NOT found at path " + filePathToAppend + ". Return without appending");
// handle it
}
}
}
Upvotes: 2