Java - Pass a variable from user input to another java file - java

I am new to Java and I have a project to do, so I have a java file and the user have to choose from a listing of files in a directory. The input from user is saved in a variable (fileName). I want to use that variable in another java file for doing some other work. I searched online but didn't find any solution that works for me. Probably I've done something wrong.
code of the first file:
public class Director {
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
public static void main(String[] args) throws IOException {
// Creates an array in which we will store the names of files and directories
String[] pathnames;
// Creates a new File instance by converting the given pathname string
// into an abstract pathname
File f = new File("C:\\Users\\miltos\\Desktop\\polimesa\\available_videos");
// Populates the array with names of files and directories
pathnames = f.list();
System.out.println("Files in the directory:");
// For each pathname in the pathnames array
for (String pathname : pathnames) {
// Print the names of files and directories
System.out.println(pathname);
}
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter file name");
String fileName = myObj.nextLine();
File source = new File("C:\\Users\\miltos\\Desktop\\polimesa\\available_videos\\" + fileName);
File dest = new File("C:\\Users\\miltos\\Desktop\\polimesa\\raw_videos\\" + fileName);
copyFileUsingStream(source, dest);
}
}
code of the second file that i want to use the input:
public class TestFFMpeg {
static Logger log = LogManager.getLogger(TestFFMpeg.class);
public static void main(String[] args) {
FFmpeg ffmpeg = null;
FFprobe ffprobe = null;
try {
log.debug("Initialising FFMpegClient");
ffmpeg = new FFmpeg("C:\\Users\\miltos\\ffmpeg\\bin\\ffmpeg.exe");
ffprobe = new FFprobe("C:\\Users\\miltos\\ffmpeg\\bin\\ffprobe.exe");
} catch (IOException e) {
e.printStackTrace();
}
log.debug("Creating the transcoding");
FFmpegBuilder builder = new FFmpegBuilder()
.setInput("C:\\Users\\miltos\\Desktop\\polimesa\\raw_videos\\" + filename) //updated
.addOutput("C:\\Users\\miltos\\Desktop\\polimesa\\videos\\" + filename) //updated
.setVideoBitRate(200000)
.done();
log.debug("Creating the executor");
FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe);
log.debug("Starting the transcoding");
// Run a one-pass encode
executor.createJob(builder).run();
log.debug("Transcoding finished");
}
}

I created a variable names filename in class second also, which you will pass from the class one , while creating an object of class second like
TestFFMpeg obj = new TestFFMpeg();
obj.methodInSecondClass(filename);
Second Class :
public class TestFFMpeg {
static Logger log = LogManager.getLogger(TestFFMpeg.class);
public void methodInSecondClass(String filename){
FFmpeg ffmpeg = null;
FFprobe ffprobe = null;
try {
log.debug("Initialising FFMpegClient");
ffmpeg = new FFmpeg("C:\\Users\\miltos\\ffmpeg\\bin\\ffmpeg.exe");
ffprobe = new FFprobe("C:\\Users\\miltos\\ffmpeg\\bin\\ffprobe.exe");
} catch (IOException e) {
e.printStackTrace();
}
log.debug("Creating the transcoding");
FFmpegBuilder builder = new FFmpegBuilder()
.setInput("C:\\Users\\miltos\\Desktop\\polimesa\\available_videos\\"+filename) //this is where i want the same variable
.addOutput("C:\\Users\\miltos\\Desktop\\polimesa\\videos\\"+filename) //this is where i want the same variable
.setVideoBitRate(200000)
.done();
log.debug("Creating the executor");
FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe);
log.debug("Starting the transcoding");
// Run a one-pass encode
executor.createJob(builder).run();
log.debug("Transcoding finished");
}
}

Related

Java File.renamTo not working

I have made the code which renames all the jpg files in a directory from 1 to n (number of files)..
if there were let say 50 jpg files that after running the program all the files are renamed to 1.jpg ,2.jpg and so on till 50.jpg
But i am facing the problem if I manually rename the file let say 50.jpg to aaa.jpg then again running the program doesn't rename that file
I have wasted one day to resove that issue
Kindly help me
Code:
public class Renaming {
private static String path; // string for storing the path
public static void main(String[] args) {
FileReader fileReader = null; // filereader for opening the file
BufferedReader bufferedReader = null; // buffered reader for buffering the data of file
try{
fileReader = new FileReader("input.txt"); // making the filereader object and paasing the file name
bufferedReader = new BufferedReader(fileReader); //making the buffered Reader object
path=bufferedReader.readLine();
fileReader.close();
bufferedReader.close();
}
catch (FileNotFoundException e) { // Exception when file is not found
e.printStackTrace();
}
catch (IOException e) { // IOException
e.printStackTrace();
}
finally {
File directory=new File(path);
File[] files= directory.listFiles(); // Storing the all the files in Array
int file_counter=1;
for(int file_no=0;file_no<files.length;file_no++){
String Extension=getFileExtension(files[file_no]); //getting the filw extension
if (files[file_no].isFile() && (Extension .equals("jpg")|| Extension.equals("JPG"))){ // checking that if file is of jpg type then apply renaming // checking thaat if it is file
File new_file = new File(path+"\\"+files[file_no].getName()); //making the new file
new_file.renameTo(new File(path+"\\"+String.valueOf(file_no+1)+".jpg")); //Renaming the file
System.out.println(new_file.toString());
file_counter++; // incrementing the file counter
}
}
}
}
private static String getFileExtension(File file) { //utility function for getting the file extension
String name = file.getName();
try {
return name.substring(name.lastIndexOf(".") + 1); // gettingf the extension name after .
} catch (Exception e) {
return "";
}
}`
first of all, you should use the path separator / . It's work on Windows, Linux and Mac OS.
This is my version of your problem to rename all files into a folder provide. Hope this will help you. I use last JDK version to speed up and reduce the code.
public class App {
private String path = null;
public static int index = 1;
public App(String path){
if (Files.isDirectory(Paths.get( path ))) {
this.path = path;
}
}
public void rename() throws IOException{
if ( this.path != null){
Files.list(Paths.get( this.path ))
.forEach( f ->
{
String fileName = f.getFileName().toString();
String extension = fileName.replaceAll("^.*\\.([^.]+)$", "$1");
try {
Files.move( f ,Paths.get( this.path + "/" + App.index + "." + extension));
App.index++;
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
}
public static void main(String[] args) throws IOException {
App app = new App("c:/Temp/");
app.rename();
}
}

How do I create stubs for IO files to unit test in Java?

For a testing course assignment, I need to create unit tests for my already-coded system using JUnit. My system is heavily dependent on each other and it also writes/reads from a couple of text files on my disk.
I realize I have to eliminate all dependancies to successfully unit test, I just don't know how to create stubs for Files.
Any help in code, tools or concepts is welcome
import Objs.*;
import java.io.*;
import java.net.URL;
import java.util.Scanner;
/**
*This class communicates with the users file by writing to it, reading from it, searching, deleting...
*
*/
public class users {
public static File usersFile = new File("usersFile.txt");
public static PrintWriter writer;
static Scanner read ;
public static void write(userObj u){
try {
String gather = read();
String newUser = u.toString();
writer = new PrintWriter(usersFile);
writer.append(gather).append(newUser).append("\n");
writer.close();
System.out.println("The users' file has been updated");
}
catch(FileNotFoundException ex){
System.out.print("file not found");
}
}
public static String read(){
String f = null;
try {
read = new Scanner(usersFile);
StringBuilder gather = new StringBuilder();
while(read.hasNext()){
gather.append(read.nextLine()).append("\n");
}
f = gather.toString();
}
catch(FileNotFoundException ex){
System.out.print("file not found");
}
return f;
}
public static userObj search(String s){
userObj foundUser = null;
try {
read = new Scanner(usersFile);
String st=null;
while(read.hasNext()){
if (read.next().equalsIgnoreCase(s)){
foundUser = new userObj();
foundUser.name = s;
foundUser.setType(read.next().charAt(0));
foundUser.credit = read.nextDouble();
}
}
}
catch(FileNotFoundException ex){
System.out.print("file not found");
}
return foundUser;
}
public static void remove(userObj u){
String s = u.name;
if (search(s) == null){
return;}
try {
read = new Scanner(usersFile);
StringBuilder gather = new StringBuilder();
while(read.hasNext()){
String info = read.nextLine();
if (info.startsWith(s)){
continue;
}
gather.append(info).append("\n");
}
writer = new PrintWriter(usersFile);
writer.append(gather).append("\n");
writer.close();
System.out.println("The user has been deleted");
}
catch(FileNotFoundException ex){
System.out.print("file not found");
}}
public static void update(userObj u){
remove(u);
write(u);
}
}
You don't need to create "stubs for files", you need to create "stub for reading from an InputStream".
For read, search, and remove you're using Scanner, which accepts an InputStream as one of its overloaded constructors. If you add an InputStream parameter, you can use that to construct your Scanner. With normal use, you can pass a FileInputStream, while using a StringBufferInputStream for testing.
For write and remove you're using a PrintWriter, which accepts an OutputStream as one of its overloaded constructors. If you add an OutputStream parameter, you can use that to construct your PrintWriter. With normal use, you can pass a FileOutputStream, while using a ByteArrayOutputStream for testing. If you want to read the result as a string from your test, use toString(String charsetName).
public class Users {
...
public static void write(UserObj u, InputStream input, OutputStream output) {
...
String gather = read(input);
...
writer = new PrintWriter(output);
...
}
public static String read(InputStream input) {
...
read = new Scanner(input);
...
}
public static UserObj search(String s, InputStream input) {
...
read = new Scanner(input);
...
}
public static void remove(UserObj u, InputStream input, OutputStream output) {
...
read = new Scanner(input);
...
writer = new PrintWriter(output);
...
}
public static void update(UserObj u, InputStream input, OutputStream output) {
remove(u, input, output);
write(u, input, output);
}
}
// Client code example
FileInputStream input = new FileInputStream("usersFile.txt");
FileOutputStream output = new FileOutputStream("usersFile.txt");
...
Users.write(myUser, input, output);
...
String result = Users.read(input);
...
myUser = Users.search(myString, input);
...
Users.remove(myUser, input, output);
...
Users.update(myUser, input, output);
// Testing code example
StringBufferInputStream input = new StringBufferInputStream("...");
ByteArrayOutputStream output = new ByteArrayOutputStream();
...
Users.write(myUser, input, output);
...
String result = Users.read(input);
...
myUser = Users.search(myString, input);
...
Users.remove(myUser, input, output);
...
Users.update(myUser, input, output);
...
result = output.toString("UTF-8"); // see docs for other legal charset names

Can't copy internal file to user's computer

I have a program that requires that an internal file (DICTIONARY) be copied to the user's computer into the folder defined like so:
private static final String DIC_NAME = "WordHelp.dic";
private static final String DIC_FOLDER = System.getProperty("user.home");
private static final String PATH_SEP = System.getProperty("file.separator");
public static final String DICTIONARY = DIC_FOLDER + PATH_SEP + DIC_NAME;
Here's what works on MY computer, where all the Java stuff is:
public static void createDictionaryIfNecessary() throws IOException{
Path out_path = FileSystems.getDefault().getPath(DICTIONARY);
boolean dic_exists = Files.exists(out_path,
new LinkOption[]{LinkOption.NOFOLLOW_LINKS});
if(dic_exists)
return;
File file = new File("src/dictionary"); // here's problem for user ************
Path in_path = file.toPath();
try {
Files.copy(in_path, out_path,
REPLACE_EXISTING, COPY_ATTRIBUTES, NOFOLLOW_LINKS);
} catch (IOException e) { JOptionPane.showMessageDialog(null, e); }
}
But user gets this error:
java.nio.file.NoSuchFileException: src\dictionary
SOURCE file (internal to .jar file) can't be found.
If I look at in_path while debugging, the value is:
(sun.nio.fs.Windowspath) src/dictionary
And below is a bunch of info about in_path:
This all works on MY computer and I could have sworn that it ONCE worked on a user's computer...
How should I define file (see line with ********** to enable copying internal file (src/dictionary) onto a user's computer?
Here's Netbeans project view:
I worked around it by using a Scanner to read individual strings from the internal file instead of using Files.copy. Here's the code. (It's not quite as fast using Scanner, but it works.)
public static void write(FileOutputStream outfile, String s) {
try {
for(int i = 0; i < s.length(); i++)
outfile.write(s.charAt(i));
outfile.write(13); outfile.write(10);
} catch (IOException ex) {JOptionPane.showMessageDialog(null, ex);}
}
public static Scanner openDic(){
InputStream myStream = null;
try { myStream = Class.forName("masterwords.Masterwords").getClassLoader()
.getResourceAsStream("dictionary");
}catch (ClassNotFoundException ex) {/* ... */}
return new Scanner(myStream).useDelimiter("\r");
}
public static void createDictionaryIfNecessary(){
Path out_path = FileSystems.getDefault().getPath(DICTIONARY);
if(Files.exists(out_path, new LinkOption[]{LinkOption.NOFOLLOW_LINKS})) return;
FileOutputStream outStream = null;
try {outStream = new FileOutputStream(out_path.toFile());}
catch (FileNotFoundException ex) {JOptionPane.showMessageDialog(null,ex);}
Scanner scInternalDic = IO.openDic();
while(scInternalDic.hasNext()){
Utilities.write(outStream,scInternalDic.next());
}
try {outStream.close();}
catch (IOException ex) {JOptionPane.showMessageDialog(null,ex);}
scInternalDic.close();
}

How to copy file from one location to another location?

I want to copy a file from one location to another location in Java. What is the best way to do this?
Here is what I have so far:
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
public class TestArrayList {
public static void main(String[] args) {
File f = new File(
"D:\\CBSE_Demo\\Demo_original\\fscommand\\contentplayer\\config");
List<String>temp=new ArrayList<String>();
temp.add(0, "N33");
temp.add(1, "N1417");
temp.add(2, "N331");
File[] matchingFiles = null;
for(final String temp1: temp){
matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(temp1);
}
});
System.out.println("size>>--"+matchingFiles.length);
}
}
}
This does not copy the file, what is the best way to do this?
You can use this (or any variant):
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Also, I'd recommend using File.separator or / instead of \\ to make it compliant across multiple OS, question/answer on this available here.
Since you're not sure how to temporarily store files, take a look at ArrayList:
List<File> files = new ArrayList();
files.add(foundFile);
To move a List of files into a single directory:
List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
Files.copy(file.toPath(),
(new File(path + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
Update:
see also
https://stackoverflow.com/a/67179064/1847899
Using Stream
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
Using Channel
private static void copyFileUsingChannel(File source, File dest) throws IOException {
FileChannel sourceChannel = null;
FileChannel destChannel = null;
try {
sourceChannel = new FileInputStream(source).getChannel();
destChannel = new FileOutputStream(dest).getChannel();
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
}finally{
sourceChannel.close();
destChannel.close();
}
}
Using Apache Commons IO lib:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}
Using Java SE 7 Files class:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
Or try Googles Guava :
https://github.com/google/guava
docs:
https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/io/Files.html
Use the New Java File classes in Java >=7.
Create the below method and import the necessary libs.
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
Use the created method as below within main:
File dirFrom = new File(fileFrom);
File dirTo = new File(fileTo);
try {
copyFile(dirFrom, dirTo);
} catch (IOException ex) {
Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);
}
NB:- fileFrom is the file that you want to copy to a new file fileTo in a different folder.
Credits - #Scott: Standard concise way to copy a file in Java?
public static void copyFile(File oldLocation, File newLocation) throws IOException {
if ( oldLocation.exists( )) {
BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
try {
byte[] buff = new byte[8192];
int numChars;
while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
writer.write( buff, 0, numChars );
}
} catch( IOException ex ) {
throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
} finally {
try {
if ( reader != null ){
writer.close();
reader.close();
}
} catch( IOException ex ){
Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
} else {
throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original).
Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.
public static void main(String[] args) throws IOException {
String destFolderPath = "D:/TestFile/abc";
String fileName = "pqr.xlsx";
String sourceFilePath= "D:/TestFile/xyz.xlsx";
File f = new File(destFolderPath);
if(f.mkdir()){
System.out.println("Directory created!!!!");
}
else {
System.out.println("Directory Exists!!!!");
}
f= new File(destFolderPath,fileName);
if(f.createNewFile()) {
System.out.println("File Created!!!!");
} else {
System.out.println("File exists!!!!");
}
Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
System.out.println("Copy done!!!!!!!!!!!!!!");
}
You can do it with the Java 8 Streaming API, PrintWriter and the Files API
try (PrintWriter pw = new PrintWriter(new File("destination-path"), StandardCharsets.UTF_8)) {
Files.readAllLines(Path.of("src/test/resources/source-file.something"), StandardCharsets.UTF_8)
.forEach(pw::println);
}
If you want to modify the content on-the-fly while copying, check out this link for the extended example https://overflowed.dev/blog/copy-file-and-modify-with-java-streams/
I modified one of the answers to make it a bit more efficient.
public void copy(){
InputStream in = null;
try {
in = new FileInputStream(Files);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
OutputStream out = new FileOutputStream();
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
while (true) {
int len = 0;
try {
if (!((len = in.read(buf)) > 0)) break;
} catch (IOException e) {
e.printStackTrace();
}
try {
out.write(buf, 0, len);
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void moveFile() {
copy();
File dir = getFilesDir();
File file = new File(dir, "my_filename");
boolean deleted = file.delete();
}
Files.exists()
Files.createDirectory()
Files.copy()
Overwriting Existing Files:
Files.move()
Files.delete()
Files.walkFileTree()
enter link description here
You can use
FileUtils.copy(sourceFile, destinationFile);
https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

Appending multiple files into one

I have 4 different files in some locations like:
D:\1.txt
D:\2.txt
D:\3.txt and
D:\4.txt
I need to create a new file as NewFile.txt, It should contains all the contents present in the above files 1.txt, 2.txt,3.txt 4.txt.......
All Data should present in the New Single file(NewFile.txt)..
Please suggest me some idea to do the same in java or Groovy....
Here's one way to do it in Groovy:
// Get a writer to your new file
new File( '/tmp/newfile.txt' ).withWriter { w ->
// For each input file path
['/tmp/1.txt', '/tmp/2.txt', '/tmp/3.txt'].each { f ->
// Get a reader for the input file
new File( f ).withReader { r ->
// And write data from the input into the output
w << r << '\n'
}
}
}
The advantage of doing it this way (over calling getText on each of the source files) is that it will not need to load the entire file into memory before writing its contents out to newfile. If one of your files was immense, the other method could fail.
This is in groovy
def allContentFile = new File("D:/NewFile.txt")
def fileLocations = ['D:/1.txt' , 'D:/2.txt' , 'D:/3.txt' , 'D:/4.txt']
fileLocations.each{ allContentFile.append(new File(it).getText()) }
i am showing you the way it is to be done in java:
public class Readdfiles {
public static void main(String args[]) throws Exception
{
String []filename={"C:\\WORK_Saurabh\\1.txt","C:\\WORK_Saurabh\\2.txt"};
File file=new File("C:\\WORK_Saurabh\\new.txt");
FileWriter output=new FileWriter(file);
try
{
for(int i=0;i<filename.length;i++)
{
BufferedReader objBufferedReader = new BufferedReader(new FileReader(getDictionaryFilePath(filename[i])));
String line;
while ((line = objBufferedReader.readLine())!=null )
{
line=line.replace(" ","");
output.write(line);
}
objBufferedReader.close();
}
output.close();
}
catch (Exception e)
{
throw new Exception (e);
}
}
public static String getDictionaryFilePath(String filename) throws Exception
{
String dictionaryFolderPath = null;
File configFolder = new File(filename);
try
{
dictionaryFolderPath = configFolder.getAbsolutePath();
}
catch (Exception e)
{
throw new Exception (e);
}
return dictionaryFolderPath;
}
}
tell me if you have any doubts
I tried solving this and i found its quite easy if you copy the contents to an array and write the array to a different file
public class Fileread
{
public static File read(File f,File f1) throws FileNotFoundException
{
File file3=new File("C:\\New folder\\file3.txt");
PrintWriter output=new PrintWriter(file3);
ArrayList arr=new ArrayList();
Scanner sc=new Scanner(f);
Scanner sc1=new Scanner(f1);
while(sc.hasNext())
{
arr.add(sc.next());
}
while(sc1.hasNext())
{
arr.add(sc1.next());
}
output.print(arr);
output.close();
return file3;
}
/**
*
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) {
try
{
File file1=new File("C:\\New folder\\file1.txt");
File file2=new File("C:\\New folder\\file2.txt");
File file3=read(file1,file2);
Scanner sc=new Scanner(file3);
while(sc.hasNext())
System.out.print(sc.next());
}
catch(Exception e)
{
System.out.printf("Error :%s",e);
}
}
}
You can do something like this in Java. Hope it helps you resolve your problem:
import java.io.*;
class FileRead {
public void readFile(String[] args) {
for (String textfile : args) {
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(textfile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
// Write to the new file
FileWriter filestream = new FileWriter("Combination.txt",true);
BufferedWriter out = new BufferedWriter(filestream);
out.write(strLine);
//Close the output stream
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
public static void main(String args[]) {
FileRead myReader = new FileRead();
String fileArray[] = {"file1.txt", "file2.txt", "file3.txt", "file4.txt"};
myReader.readFile(fileArray);
}
}
One liner example:
def out = new File(".all_profiles")
['.bash_profile', '.bashrc', '.zshrc'].each {out << new File(it).text}
OR
['.bash_profile', '.bashrc', '.zshrc'].collect{new File(it)}.each{out << it.text}
Tim's implementation is better if you have big files.
public static void main(String[] args) throws IOException {
List<String> files=new ArrayList<String>();
for(int i=10;i<14;i++)
files.add("C://opt/Test/test"+i+".csv");
String destFile ="C://opt/Test/test.csv";
System.out.println("TO "+destFile);
long st=System.currentTimeMillis();
mergefiles(files, destFile);
System.out.println("DONE."+(st-System.currentTimeMillis()));
}
public static void mergefiles(List<String> files,String destFile){
Path outFile = Paths.get(destFile);
try(FileChannel out=FileChannel.open(outFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
for(String file:files) {
Path inFile=Paths.get(file);
System.out.println(inFile);
try(FileChannel in=FileChannel.open(inFile, StandardOpenOption.READ)) {
for(long p=0, l=in.size(); p<l; )
p+=in.transferTo(p, l-p, out);
}catch (IOException e) {
System.out.println("ERROR:: "+e.getMessage());
}
out.write(ByteBuffer.wrap("\n".getBytes()));
}
} catch (IOException e) {
System.out.println("ERROR:: "+e.getMessage());
}
}

Categories

Resources