1

I am new to file handling in Java. My input file is a csv file with a number of columns. My objective is to create a new file each time I encounter a different value in the input .csv file and append to it if the file already exists but the file is being overwritten instead, which is apparent by keeping watch over the file size when the program is running.


Example Input File:

100, 1000
200, 2000
200, 3000
300, 4000

Example Output Files (Expected):
100.csv:

100,1000

200.csv:

200, 2000
200, 3000

300.csv:

300, 4000

Example Output Files (Actual):

100.csv:

100, 1000

200.csv:

200,3000

300.csv:

300,4000

Code:

public class App {
    public static void main(String[] args) throws Exception {
        
        List<File> filesInFolder = Files.walk(Paths.get("D:/java-projects/task_usage"))
        .filter(Files::isRegularFile)
        .map(Path::toFile)
        .collect(Collectors.toList());
        for(File file : filesInFolder) {
            Sheet sheet = new Sheet();
            String inputFile = file.getAbsolutePath();

            BufferedReader br = new BufferedReader(new FileReader(inputFile));
            String line = "";
            while ((line = br.readLine()) != null) {
                sheet.add(line.split(","));
            }
            br.close();

            for(String[] row : sheet.getSheet()) {
                String outputFile = "H:/Files/" + row[3] + ".csv";
                BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
                bw.append(String.join(",", row));
                bw.append("\n");
                bw.close();
            }
        }
    }
}


public class Sheet {
    private List<String[]> sheet = null;

    public Sheet() {
        sheet = new ArrayList<>();
    }

    // adds a new row to the sheet
    public Boolean add(String[] row) {
        Long diff = Long.parseLong(row[1]) - Long.parseLong(row[0]);
        String[] newRow = new String[row.length + 1];
        newRow[0] = diff + "";
        for(Integer i = 1, j = 0; j < row.length; i++) {
            newRow[i] = row[j++];
        }
        return this.sheet.add(newRow);
    }

    // retrieves a row from the sheet
    public String[] get(Integer index) {
        return this.sheet.get(index);
    }

    public void setSheet(List<String[]> sheet) {
        this.sheet = sheet;
    }

    public List<String[]> getSheet() {
        return this.sheet;
    }

}



public class SheetSorter {

    // sorts the sheet
    public static Sheet sortSheet(Sheet sheet) {
        List<String[]> list = sheet.getSheet().stream().collect(Collectors.toList());
        Collections.sort(list, new Comparator<String[]>() {
            @Override
            public int compare(String[] arr1, String[] arr2) {
                if (Long.parseLong(arr1[3]) == Long.parseLong(arr2[3])) {
                    return (int) (Long.parseLong(arr1[4]) - Long.parseLong(arr2[4]));
                }
                else {
                    return (int) (Long.parseLong(arr1[3]) - Long.parseLong(arr2[3]));
                }
            }
        });
        sheet.setSheet(list);
        return sheet;
    }
}

Where have I gone wrong?

lucidbrot
  • 5,378
  • 3
  • 39
  • 68
  • The table is seen properly in the "this is how your post will look like" section of the edit view. It seems it does not display correctly in the actual post. How do I fix that? – Shyam Deshmukh Apr 24 '22 at 10:42
  • Just from a quick search, I don't actually know, what I notice is that [this answer](https://stackoverflow.com/a/1625263/2550406) uses a second argument `true` to `FileWriter`, which is called `append` [here](https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html). Maybe your way is correct too, but worth checking whether this other way would work – lucidbrot Apr 24 '22 at 10:44
  • Regarding the table, yes sadly the preview supports more markdown syntax than the actual view sometimes. I guess you can format it as a code block instead, then it does not look so broken. If it is relevant at all – lucidbrot Apr 24 '22 at 10:45
  • Nah, the code formatted table is even worse! – Shyam Deshmukh Apr 24 '22 at 10:46
  • 1
    @lucidbrot, the answer worked! – Shyam Deshmukh Apr 24 '22 at 10:54
  • That's wonderful! But also confusing to me then why your approach did not work. I haven't seen clear documentation about this yet. Maybe the bufferedwriter only `append()`ed to what it already knew, and since you recreate it everytime... shrug – lucidbrot Apr 24 '22 at 10:54
  • 2
    The `append(...)` methods of a writer have nothing to do with appending to a file. They are an implementation of the `Appendable` interface, which has a specific use case in combination with `java.util.Formatter`. – Mark Rotteveel Apr 24 '22 at 11:01
  • 1
    @lucidbrot, its simple. The `FileWriter` as the name suggests, is used primarily for writing to a file rather than appending to a file. It creates a new file irrespective of whether the file is present unless exclusively asked not to. – kesarling He-Him Apr 24 '22 at 11:02

0 Answers0