Kent Wong
Kent Wong

Reputation: 581

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

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 

Upvotes: 5

Views: 163

Answers (2)

ttoocs
ttoocs

Reputation: 11

Agreeing with others: You delete your progress every time you 'touch' your masterDump file. Here is my version:

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

public class FilePrepender // class name
{
     public static void main (String [] args)
    {
        //Generates the string for the output for the right PC.
        String OUTFILE="Output"+File.separator+"masterDump.txt";

       // make a giant dump file which we will append all read files into
        try {
            new File("Output").mkdirs();
            File megaDumpFile = new File(OUTFILE);
            megaDumpFile.createNewFile();

        } catch (IOException e) {
            System.out.println("Something weird occured!");
        }

        File folder = new File(".");
//      FileFilter filter = new istext();
//      File[] listOfFiles = folder.listFiles( filter );

     //grab file names
        File[] listOfFiles = folder.listFiles();

        try {
            FileOutputStream fout = new FileOutputStream ( new File(OUTFILE));
            PrintWriter pout = new PrintWriter( fout ); 
            for (int j = 0; j < listOfFiles.length; j++){

                //Hacky fix cause java is hard:
                if ( ! listOfFiles[j].getName().endsWith(".txt")) { continue ; }

                //append file name for mega dump file
                pout.println(listOfFiles[j].getName());  // Append File-name
                pout.flush(); //Probably a better way than this, but eh.

                //Copy the file's text
                Files.copy(listOfFiles[j].toPath(), fout);
                fout.flush(); //Again, eh.
            }
            pout.close();
            pout.close();
            }
            catch (IOException e) {

            }

        }
}
/*  Ugh, IDK how to java. (This is the non-hacky way, but idk how to.)

public class istext implements FileFilter {
    public static void accept(File pathname){
        return( pathname.getName().endsWith(".txt"));
    }
}

*/

Upvotes: 1

DAXaholic
DAXaholic

Reputation: 35358

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 

Upvotes: 2

Related Questions