【问题标题】:count the filenames character and limit the file size to show Joptionpane计算文件名字符并限制文件大小以显示 Joptionpane
【发布时间】:2020-02-23 05:08:32
【问题描述】:

我正在使用 Jfilechooser,如果我选择文件,它将计算文件名的字符数,但是如果文件超过 3kb,它将显示 Joptionpane。我的问题是即使文件是 0kb,Joptionpane 也会出来,我不知道我的代码是否正确。

private int countWords(File f) {

    int filelength = 0;

    // Count of words.
    filelength = f.getName().length();

    double bytes = f.length();
    double kilobytes = (bytes / 1024);
    double limit = (1024 * 3);
    if (f.exists() && (kilobytes >= limit)) {
        JOptionPane.showConfirmDialog(null, "File Size:" + kilobytes + "KB", "Message Interrupted",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    }

    return filelength;

}

【问题讨论】:

  • 为什么不打印出字节或将其显示在 JOptionPane 中?

标签: java filenames filesize


【解决方案1】:

这...

double kilobytes = (bytes / 1024);

正在获取文件字节并将其转换为千字节(1216 bytes1.1875

这...

limit = (1024 * 3);

取 3(千字节)并将其转换为字节 (3072.0)

因此,您最终会将 1.8753072 进行比较,这是不正确的。而是删除其中一个转换,例如...

double bytes = f.length();
//double kilobytes = (bytes / 1024);
double limit = (1024 * 3);

if (f.exists() && (bytes >= limit)) { ... }

在我的测试中,我对 0kb 文件没有任何问题

【讨论】:

  • 它工作。谢谢你。双字节 = f.length();双千字节=(字节/ 1024);双重限制 = (1024 * 3); if (f.exists() && (bytes >= limit)) { JOptionPane.showConfirmDialog(null, "File Size:" + kilobytes + "KB", "Message Interrupted", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); } 返回文件长度; }
猜你喜欢
  • 2016-09-19
  • 1970-01-01
  • 2015-03-16
  • 2019-03-05
  • 2014-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多