BufferedWriter 不写入所有信息

BufferedWriter not writing ALL the information

我正在制作一个简单的教程程序,用户在其中输入一些数据,然后将数据写入文本文件,然后读取文本文件并显示数据。但是,并非所有数据都被写入文本文件。请查看以下内容:

这是我的代码:

package chasi.fecalMatter.ExcrementalProgram;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JOptionPane;

public class RedundantExcrement {

    static String inputName = JOptionPane.showInputDialog("Please input your FULL name:");
    static String inputUsername = JOptionPane.showInputDialog("Please input your desired Username:");
    static String inputJobTitle = JOptionPane.showInputDialog("Please input your Job title:");
    static String inputSalary = JOptionPane.showInputDialog("Please input your monthly salary:");

    static int convertedSalary = 0; /*Convert salary from String to int*/
    static int benefitDeduction = 0;

    static String empFileName = inputUsername+"INFO";
    static BufferedWriter bwriter = null;

    public static void main (String[] args) throws IOException {
        //Catch NumberFormatException.
        try {
            Integer.parseInt(inputSalary);
        } catch (NumberFormatException nfEx) {
            JOptionPane.showMessageDialog(null, "Please ensure that " +
                    "your salary is entered in NUMERIC form.", "ERROR!", 2);
            return;
        }

        //Specify instructions as regard salary -to- Benefit deduction ratio
        if (convertedSalary >= 3500) {
            benefitDeduction = 300;
        } else {
            benefitDeduction = 180;
        }

    try { /*Catches IOException AND NullPointerException*/ 
            FileWriter fwriter = new FileWriter(empFileName);
            bwriter = new BufferedWriter(fwriter);

            bwriter.write(inputName);
            bwriter.newLine();
            bwriter.write(inputJobTitle);
            bwriter.newLine();
            bwriter.write(inputSalary);
            bwriter.newLine();
            bwriter.write(benefitDeduction);
            bwriter.newLine();
            bwriter.write("----------");
            bwriter.newLine();              
        } catch (IOException | NullPointerException ionpEx) {
            JOptionPane.showMessageDialog(null, "An ERROR has occured", "ERROR!", 2);
            return;
        } finally { /*CLOSE the writer*/                
            try{
                if (bwriter != null) {
                    bwriter.close();
                }
            } catch (IOException ioEx2) {
                JOptionPane.showMessageDialog(null, "ERROR!");
                return;
            }
        }
    }
}

如您所见,我使用 int convertedSalary 将 user-inputted inputSalary 从字符串转换为数字。在我的方法中,我使用

try {
    Integer.parseInt(inputSalary);
} catch (NumberFormatException nfEx) {
    JOptionPane.showMessageDialog(null, "Please ensure that " +
            "your salary is entered in NUMERIC form.", "ERROR!", 2);
    return;
}

为了掩饰。它稍后(应该)由 BufferedWriter 写入。

我也有这个代码:

try {
    Integer.parseInt(inputSalary);
} catch (NumberFormatException nfEx) {
    JOptionPane.showMessageDialog(null, "Please ensure that " +
                "your salary is entered in NUMERIC form.", "ERROR!", 2);
    return;
}

为了根据用户的工资值改变我的benefitDeduction的值。

然而,benefitDeduction 被写入文本文件,但我得到的是:

如有帮助,谢谢!

看看API

public void write(int c)
   throws IOException

Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.

这意味着int实际上是一个char,将根据Unicode/ASCII table.

进行转换

要写入整数值,请使用 bwriter.writer(String.valueOf(benefitDeduction));

你的问题是,当你写你的数字时,这些值被写成二进制数字而不是文本数字。你可以通过 writer.write("" + myNumber);

来解决这个问题

您的代码有两个主要问题。

首先,您实际上并没有将 ParseInt 中的值分配给 convertedSalary 变量。因此,它将始终为零。

再说一次,您也没有将 convertedSalary 写入文件。

其次,我认为您混淆了 BufferedWriter.write(int)PrintWriter.print(int)BufferedWriter 将打印此整数表示的字符,如果它在 065535 之间(或者如果不是,则它的低两个字节中的任何内容)。

所以,如果你的整数是,例如,65,你将打印的是字符 A,其值在 Unicode 中是 65

所以也许您应该在那里使用 PrintWriter 而不是 BufferedWriter。或者按照其他答案的建议将数字转换为字符串。

正如其他答案所指出的,您的问题是write(int)的调用。但是不用担心转换,您还可以使用 StringBuilder 先创建您的文本,然后调用 write(String) 来编写它。这样你就不必担心 benefitDeduction:

的类型
final String inputName = "Tom";
final String inputJobTitle = "Developer";
final String inputSalary = "1337";
final int benefitDeduction = 180;

try(final BufferedWriter bwriter = new BufferedWriter(new FileWriter("blub.txt"))) {
    final StringBuilder builder = new StringBuilder(inputName);
    builder.append("\n").append(inputJobTitle);
    builder.append("\n").append(inputSalary);
    builder.append("\n").append(benefitDeduction);
    builder.append("\n----------\n");
    bwriter.write(builder.toString());
} catch (IOException | NullPointerException ex) {
  JOptionPane.showMessageDialog(null, "An ERROR has occured", "ERROR!", 2);
  return;
}

另请注意,我使用 try-with-resources statement 来处理 BufferedWriter。它将处理资源并为您关闭它。无需手动执行此操作。

以上代码将以下数据写入文件"blub.txt":

Tom
Developer
1337
180
----------

正如我已经在评论中写的那样,您没有为变量分配新值 convertedSalary

换行:

Integer.parseInt(inputSalary);

至:

convertedSalary = Integer.parseInt(inputSalary);

做到这一点。

Integer.parseInt(inputSalary) //returns一个整数

引自JDK: Integer.parseInt(); = "Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method."

您的代码应为:

convertedInt = Integer.parseInt(inputSalary);