[英]How do I get the file size of a given string?
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.
我真的需要这样做,因为将字符串转换为文本文件并获取大小然后删除文件是行不通的。
Example using java.nio.Files
:使用
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
:使用
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;
}
All you need is to count bytes
required to store you string, because one character could take more than one byte.您只需要计算存储字符串所需的
bytes
数,因为一个字符可能占用多个字节。
When you write n
bytes to the file, this file is going to have exactly this amount of bytes.当您将
n
个字节写入文件时,该文件将恰好具有这个字节数。 Do use String.getBytes()
to calculate it.请使用
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.