计算文件名字符并限制文件大小以显示Joptionpane

问题描述 投票:0回答:1

我正在使用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;

}
java filenames filesize
1个回答
0
投票

此...

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文件没有任何问题

© www.soinside.com 2019 - 2024. All rights reserved.