0

I need to get the size of a file, but I keep on getting 0 as the size, which is not the actual size.

private void dodAlgorithm() throws IOException {
        int count;
        int randomValue;
        long fileSize;
        File file = new File(filename);
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));  
        SecureRandom random = new SecureRandom();

        if(file.exists()) {
            fileSize = file.length();
        }
        else {
            JOptionPane.showMessageDialog(null, "");
            return;
        }

        // Overwrite the file with 0's.
        for(count = 0; count < fileSize; count++) { 
            writer.write(0);
        }

        // Overwrite the file with 1's.
        for(count = 0; count < fileSize; count++) {
            writer.write(1);
        }

        // Overwrite the file with random numbers.
        for(count = 0; count < fileSize; count++) {
            randomValue = random.nextInt();
            writer.write(randomValue);
            txtHexValues.append(Integer.toHexString(randomValue) + " ");
        }

        // Close the file and delete it.
        writer.close();
        file.delete();

        JOptionPane.showMessageDialog(null, "Done!");
    }
2
Contributors
1
Reply
13
Views
2 Years
Discussion Span
Last Post by sepp2k
1

You check the file size after you've already opened the file for writing. Since opening a file for writing creates an empty file with that name (overriding the existing file if it exists), this means that a) the file will always exist and b) it's size will always be 0.

You need to check the size before opening the file instead.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.