如何在 JTextField 中显示从 JFileChooser 选择的文件的大小?当我使用 f.getTotalSpace()
时,系统会显示我的电脑的总磁盘空间,这不是我想要的。
private void jButtonAttachActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser jc = new JFileChooser();
jc.setDialogType(JFileChooser.OPEN_DIALOG);
jc.showOpenDialog(null);
File f = jc.getSelectedFile();
if (f.length() / 1024 < 1024) {
jTextFieldAttachments.setText(f.getName() + " " + "(" + f.length() / 1024 + " KB)");
}
else if (f.length() / 1024 >= 1024) {
jTextFieldAttachments.setText(f.getName() + " " + "(" + f.length() / 1048576 + " MB)");
}
}
**EDIT by @RoeyGolzarpoor**
if (f.length() / 1024 <= 1024) {
jTextFieldAttachments.setText(f.getName() + " " + "(" + String.format("%.1f", (f.length() / 1024)) + " KB)");
}
else if (f.length() / 1024 > 1024) {
jTextFieldAttachments.setText(f.getName() + " " + "(" + String.format("%.1f", (f.length() / 1048576)) + " MB)");
}
错误
最佳答案
用途:
float kilo_bytes f.length()/1024;
Float.parseFloat(String.format("%.1f", kilo_bytes));
这将返回您的文件(以 KB
为单位)
提醒:
1024 字节 = 1 千字节
1024 kb = 1 兆字节
1024 mb = 1 Gega 字节
1024 GB = 1 太字节
关于java - 如何在 JTextField 中显示附加文件的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28141549/