1

I'm writing a program where there is some data, that I've to pick from multiple documents and make a new file.

Below is my code.

public class IndexFiles extends SwingWorker<Void, String> {
    private String inputPath;

    public IndexFiles(String inputPath) {
        this.inputPath = inputPath;
    }

    @Override
    protected Void doInBackground() throws Exception {
        File directory = new File(inputPath);
        countFilesInDirectory(directory);
        return null;
    }

    void countFilesInDirectory(File directory) throws IOException {
        System.out.println("entered");
        File[] list = directory.listFiles();
        System.out.println("length is " + list.length);
        for (int i = 0; i < list.length; i++) {
            GenerateFiles(list[i].getAbsoluteFile().toString());
        }

    }

    private void GenerateFiles(String inputfilePath) throws IOException {
        String input = inputfilePath;
        URL url = new URL("file:///" + input);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String inputLine;

        String tempPath = inputfilePath.substring(0, inputfilePath.lastIndexOf("\\") + 1);
        String secPath = tempPath.substring(0, tempPath.lastIndexOf("\\"));
        String finalPath = secPath.substring(0, secPath.lastIndexOf("\\")) + "\\OP\\";

        File outPath = new File(finalPath);
        if (!outPath.exists()) {
            outPath.mkdir();
        }
        File temp = new File(finalPath + "temp.txt");
        FileOutputStream fos = new FileOutputStream(temp, true);

        if (!temp.exists()) {
            temp.createNewFile();
        }
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
        bw.write("");
        while ((inputLine = in.readLine()) != null) {
            if (inputLine.contains("/section")) {
                break;
            }
            if (inputLine.contains("DOCTYPE")) {
                inputLine = inputLine.replace("<!DOCTYPE html>", "");
            }
            if (inputLine.contains("html")) {
                inputLine = inputLine.replaceAll(
                        "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"content-type\" content=\"text/html\" charset=\"utf-8\"/>(.*)<section>",
                        "");
            }
            if (inputLine.contains("?")) {
                inputLine = inputLine.replace("<?", "");
            }
            if (inputLine.contains("pb")) {
                inputLine = inputLine.replaceAll("pb label=\"(.*)\"?>", "");
            }
            if (!(inputLine.trim().isEmpty())) {
                bw.append(inputLine);
                bw.newLine();
            }
        }
        bw.close();
        in.close();

    }

}

This program runs fine for the first time. The file is getting created correctly. But the problem comes when I run this again, it is getting appended instead of creating a new fresh data. I'm sure that this is because of FileOutputStream fos = new FileOutputStream(temp, true);, if I remove true, each time a file is done, a new copy gets updated. But my requirement is to create a fresh data each time I run the program, instead of getting appended to the existing one.

I've say 10 files, and I run the program, the contents of all the 10 files should go into the temp file. I run it again, it should be like, I clear the temp file. Write the contents of these 10 files. but right now, I run the program, the data is written into the temp file, I run it again, it get appended with the same 10 files data. I want to replace the full content, but not individual file content. first time I run, 10 files data is written into the temp file. I run it again, The temp file should be cleared and write this 10 files data.

halfer
  • 19,824
  • 17
  • 99
  • 186
Rakesh
  • 564
  • 1
  • 8
  • 25
  • Duplicate of [Java overwriting an existing output file](http://stackoverflow.com/questions/17957849/java-overwriting-an-existing-output-file)? – Tom Rees Apr 01 '16 at 11:27
  • I think problem is with same file name. Try appending timestamp at file name. So every time it will create new file. – sAm Apr 01 '16 at 11:28
  • Hi @TomRees, no it is not. I've clearly mentioned the problem above. – Rakesh Apr 01 '16 at 11:29
  • Hi @sAm, let me try it. ;) – Rakesh Apr 01 '16 at 11:29
  • In which case, would you mind clarifying the question - it seems people are reading it as you want to overwrite the same file each time. From sAms comment, I think you really mean you want a new file for each time you run the program. – Tom Rees Apr 01 '16 at 11:43
  • 1
    The problem is that he creates the writer several times. What he wants is that the first writer created in a run should clear the file before write, while the subseqent writers should append. I think :-) I have proposed two ways to do this in my answer. – LarsErik Apr 01 '16 at 11:51
  • Hi @LarsErik, You are correct, let me try your approach. :) – Rakesh Apr 01 '16 at 11:53
  • By the way. You are checking the file for existence after opening the FileOutputStream, so it will never happen that temp does not exist. – Alexander Apr 01 '16 at 12:10

2 Answers2

1

Choose one:

  • Create the BufferedWriter without the true-flag in countFilesInDirectory and pass it as an argument to GenerateFiles
  • Add code to delete the temp file in before the for-loop in countFilesInDirectory
LarsErik
  • 138
  • 1
  • 7
1

Use

 FileOutputStream fos = new FileOutputStream(temp);

instead of

 FileOutputStream fos = new FileOutputStream(temp, true);

For FileOutputStream(File file, boolean append) constructor if append is set to true, the data you write will be appended to the end of the file, rather than overwriting what was already there

mystery
  • 875
  • 6
  • 16