Kent W Kent W - 4 months ago 8
Java Question

Text is not appended in new file in attempt to make a text file manipulator

Problem and where I'm at: I can't append text into these new files I create with the program. Currently it only copies files but does not append them. See line with comment

"// append file name into the new file "
.

Secondly, the final dump file seems to only append the .java file, it's not reading or appending the input files.

The explanation of what I'm trying to do:

The long and short is that I am trying to make a program that will be placed into random folders with .txt files filled with data.

I need the program to


  • Look within the realm of the folder it is in only

  • Then take any .txt file and

    a) make a copy but append the original file name into the text body (at the top), inside a sub-folder like "< filenamehere.txt" into the body (at the top)

    b) then copy body contents of the original.txt
    c) take the prepended .txt file and append it to a single dump.txt file
    d) repeat this for all local txt files and keep appending to the end of the dump.txt file



So at the end, if I had 7 files, I will have 7 appended copies and 1 giant dump file containing everything of the 7 appended copies. So for example, if I had three text files, each one having only one word in them. So a.txt, b.txt, c.txt
and the three words are "Hello world !". The a.txt copy would have the contents inside

">a.txt

Hello

"

Right now it's just copying the Hello (original body content) but not appending the >a.txt. The final dump text file is not accumulating anything from the other files, but it's strangely enough picking up the source code from the .java file. So essentially, I get a //Output folder and inside are the copies of the .txt files and a megaDump.txt that manages to pick up the .java text, but no other text files are appended.

import java.io.* ;
import java.nio.file.*;

public class FilePrepender // class name
{
public static void main (String [] args)
{
// make a giant dump file which we will append all read files into
try {
new File("Output\\").mkdirs();
File megaDumpFile = new File("Output\\masterDump.txt");

if (megaDumpFile.createNewFile()) {
System.out.println("File creation success");
} else {
System.out.println("File was not made. File already exists. Please delete");
}

} catch (IOException e) {

}

//grab file names
File folder = new File(".");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
listOfFiles[i].getName();
} else if (listOfFiles[i].isDirectory()) {
//do nothing
}
}

//open files + duplicate + prepend + and append product to end of master dump file
// main for
for (int j = 0; j < listOfFiles.length; j++){
//append file name for mega dump file
String fileNameTemp = listOfFiles[j].getName(); // get file name
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Output//masterDump.txt", true)));
out.println(fileNameTemp);
out.flush();
out.close();
}
catch (IOException e) {

}

// duplicate input files
FileInputStream instream = null;
FileOutputStream outstream = null;

try {
File infile =new File(""+listOfFiles[j].getName());
File outfile =new File("Output\\"+listOfFiles[j].getName());

instream = new FileInputStream(infile);
outstream = new FileOutputStream(outfile);

byte[] buffer = new byte[1024];

int length;

// apend file name into the new file
// String fileNameTemp = listOfFiles[j].getName(); // get file name

try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Output//masterDump.txt", true)));
out.println(">"+fileNameTemp);
out.flush();
out.close();
}
catch (IOException e) {

}


// now copy contents of previous file into the new file

/*copying the contents from input stream to
* output stream using read and write methods
*/
while ((length = instream.read(buffer)) > 0){
outstream.write(buffer, 0, length);
}
//Closing the input/output file streams
instream.close();
outstream.close();

// file is copied
} catch(IOException ioe) {

}

// copy newly copied file into mega dump
try {
File infile =new File("Output\\"+listOfFiles[j]); // newly copied
File outfile =new File("Output\\masterDump.txt");

instream = new FileInputStream(infile);
outstream = new FileOutputStream(outfile);

byte[] buffer = new byte[1024];

int length;
/*copying the contents from input stream to
* output stream using read and write methods
*/
while ((length = instream.read(buffer)) > 0){
outstream.write(buffer, 0, length);
}

//Closing the input/output file streams
instream.close();
outstream.close();

// file is copied

} catch(IOException ioe) {

}

} // end for loop
} // end main
} // end class

Answer

There are quite a few issues here:

  • You use for your file paths sometimes slash, sometimes 2 backslashes and sometimes even double slashes which resulted in problems at least on my Mac. Just use regular forward slashes.

  • The code did not filter for .txt files yet, so everything which was in the current directory was processed - even the executing program itself.

  • Currently the code wrote the > sometext.txt lines directly into your masterDump.txt instead of indirectly through your file copies.

  • The code overwrote masterDump.txt for each iteration of the loop as the file was not opened in appending mode.

Following is the code which currently produces the following result when called in a folder with a.txt, b.txt and c.txt containing "Hello", "World" and "!" respectively. I hope this is the desired behavior.
Note that there is much to improve in this code, especially handling the errors as already pointed out in the comments.

Result

import java.io.* ;
import java.nio.file.*;

public class FilePrepender // class name 
{
    public static void main (String [] args)
    {
        // make a giant dump file which we will append all read files into  
        try {
            new File("Output/").mkdirs();
            File megaDumpFile = new File("Output/masterDump.txt");

            if (megaDumpFile.createNewFile()) {
                System.out.println("File creation success");
            } else {
                System.out.println("File was not made. File already exists. Please delete");
            }

        } catch (IOException e) {

        }

        //grab file names 
        File folder = new File(".");
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                listOfFiles[i].getName();
            } else if (listOfFiles[i].isDirectory()) {
                //do nothing
            }
        }

        //open files + duplicate + prepend + and append product to end of master dump file 
        // main for 
        for (int j = 0; j < listOfFiles.length; j++){
            //append file name for mega dump file 
            String fileNameTemp = listOfFiles[j].getName();  // get file name
            if (!fileNameTemp.toLowerCase().endsWith(".txt")) {
                continue;
            } 

            // duplicate input files 
            FileInputStream instream = null;
            FileOutputStream outstream = null;

            try {
                File infile =new File(""+listOfFiles[j].getName());
                File outfile =new File("Output/"+listOfFiles[j].getName());

                instream = new FileInputStream(infile);


                byte[] buffer = new byte[1024];

                int length;

                // apend file name into the new file 
                // String fileNameTemp = listOfFiles[j].getName();  // get file name 
                outstream = new FileOutputStream(outfile);
                PrintWriter out = new PrintWriter(outstream);
                out.println(">"+fileNameTemp);
                out.flush();
                out.close();

                // now copy contents of previous file into the new file 

                /*copying the contents from input stream to
                * output stream using read and write methods
                */
                outstream = new FileOutputStream(outfile, true);
                while ((length = instream.read(buffer)) > 0){
                    outstream.write(buffer, 0, length);
                }
                //Closing the input/output file streams
                instream.close();
                outstream.close();

                // file is copied 
            } catch(IOException ioe) { 

            }

            // copy newly copied file into mega dump 
            try {
                File infile =new File("Output/"+listOfFiles[j]); // newly copied 
                File outfile =new File("Output/masterDump.txt");

                instream = new FileInputStream(infile);
                outstream = new FileOutputStream(outfile, true);

                byte[] buffer = new byte[1024];

                int length;
                /*copying the contents from input stream to
                * output stream using read and write methods
                */
                while ((length = instream.read(buffer)) > 0){
                    outstream.write(buffer, 0, length);
                }

                //Closing the input/output file streams
                instream.close();
                outstream.close();

                // file is copied 

            } catch(IOException ioe) {

            }

        } // end for loop 
    } // end main 
} // end class 
Comments