【问题标题】:How do I get the file size of a given string?如何获取给定字符串的文件大小?
【发布时间】:2020-08-31 12:42:05
【问题描述】:

如果我们有一个字符串并将该字符串放入一个文本文件中......该文本文件将具有大小。是否有某种公式可以用来计算大小?我真的需要这样做,因为将字符串转换为文本文件并获取大小然后删除文件不起作用。

【问题讨论】:

  • 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. - 不查看您的代码,怎么会知道什么不起作用?
  • 不确定你的意思是字符串的长度,字符串在内存中占用的字节数?请分享代码或详细说明。同时检查此链接是否是您的意思或要求:stackoverflow.com/a/9368834/6755811
  • @VijayC 如果将字符串放入文本文件中,那么该文本文件的大小就是我想要的。
  • @EmmanuelOkafor 有 java.io.File::length 方法返回文件大小(以字节为单位)。将字符串写入文本文件后是否尝试过?
  • 问题可能是磁盘上的文件占用了额外的空间,因为操作系统在文件末尾添加了填充以将其保存在块或块的一部分中。

标签: java string text size


【解决方案1】:

使用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;
}

使用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;
}

使用字节数组长度的更简单示例:

public static int stringSize(String str) {
    return str.getBytes().length;
}

【讨论】:

  • 最后一个方案很有创意。
【解决方案2】:

您只需计算存储字符串所需的bytes,因为一个字符可能占用多个字节。

当您将n 字节写入文件时,该文件将恰好具有该字节数。请使用String.getBytes() 计算。

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
}

【讨论】:

    猜你喜欢
    • 2010-10-23
    • 1970-01-01
    • 2010-10-17
    • 2018-09-08
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    相关资源
    最近更新 更多