-2

If we had a string and we put that string into a text file... that text file would have a size. Is there some sort of formula that we could use to calculate the size? I really need to do this because turning the string into a text file and getting the size then deleting the file is not working.

  • `I really need to do this because turning the string into a text file and getting the size then deleting the file is not working.` - Without looking into your code, how will know what is not working? – Arvind Kumar Avinash Aug 31 '20 at 13:26
  • Not sure if you mean the length of the string, the bytes occupied by the string in memory? Please share code or elaborate more. Meanwhile check this link as well if this is what you meant or require: https://stackoverflow.com/a/9368834/6755811 – VijayC Aug 31 '20 at 13:34
  • @VijayC If the string was put into a text file, the size of that text file, is what I want. – Emmanuel Okafor Aug 31 '20 at 14:03
  • @EmmanuelOkafor There is [`java.io.File::length`](https://docs.oracle.com/javase/8/docs/api/java/io/File.html#length--) method returning file size in bytes. Did you try it after writing the string into a text file? – Nowhere Man Aug 31 '20 at 14:08
  • The problem may be that a file on a disk takes extra space because of the OS adding padding to the end of the file to keep it in blocks or fractions of a block. – NomadMaker Aug 31 '20 at 14:25

2 Answers2

3

Example using java.nio.Files:

public static long getStringSize(String str) throws IOException {
    Path file = Path.of("niofiles.txt");
    Files.writeString(file, str, StandardOpenOption.CREATE_NEW);
    long size = Files.size(file);
    Files.deleteIfExists(file); // cleanup
    return size;
}

Example using java.io.File:

public static long getStringSizeFile(String str) throws IOException {
    File file = new File("iofile.txt");
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
        bw.write(str);
    }
        
    long size = file.length();
    file.delete(); // cleanup
    return size;
}

Even simpler example to use length of the byte array:

public static int stringSize(String str) {
    return str.getBytes().length;
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
0

All you need is to count bytes required to store you string, because one character could take more than one byte.

When you write n bytes to the file, this file is going to have exactly this amount of bytes. Do use String.getBytes() to calculate it.

public static void main(String... args) {
    String str = "endereço";
    System.out.println(str.length());                            // 8
    System.out.println(str.getBytes(StandardCharsets.UTF_8));    // 9
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35