简体   繁体   中英

BufferedWriter not writing ALL the information

I am making a simple tutorial program in which the user inputs some data, then that data is written into a textfile, then the textfile is read and the data displayed. However, not all of the data is being written into the textfile. Please view the following:

This is my code:

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;
            }
        }
    }
}

As you can see, I use the int convertedSalary to convert the user-inputted inputSalary from a String into a number. In my method, I use

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

In order to covert it. It is later (supposed) to be written by the BufferedWriter.

I also have this code:

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

In order to change the value of my benefitDeduction depending on the value of the user's salary.

HOWEVER, the benefitDeduction is written into the text file, but instead, I get this: 运行程序的结果

Thanks if you can help!

Look at the 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.

This means that the int is actually a char and will be converted according to Unicode/ASCII table.

To write the integer value use bwriter.writer(String.valueOf(benefitDeduction));

There are two major problems with your code.

First, you are not actually assigning the value from your ParseInt to your convertedSalary variable. Hence, it will always be zero.

Then again, you are not writing convertedSalary to the file, either.

Second, I think you are confusing between BufferedWriter.write(int) and PrintWriter.print(int) . The BufferedWriter will print the character represented by this integer if it is between 0 and 65535 (or the whatever there is in its lower two bytes if it isn't).

So, if your integer is, for example, 65, what you will have printed is the character A , whose value is 65 in Unicode.

So maybe you should be using a PrintWriter rather than a BufferedWriter there. Or convert the numbers into strings as other answers have suggested.

As pointed out by the other answers, your problem is the call of write(int) . But instead of worrying about the conversion, you can also use StringBuilder to create your text first and write it with one call of write(String) . That way you don't have to worry about the type of 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;
}

Also note, that I used the try-with-resources statement to handle the BufferedWriter . It will handle the resource and closes it for you. No need to do that manually.

The above code write the following data into the file "blub.txt" :

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

And as I already wrote in the comment, you're not assigning a new value to the variable convertedSalary .

Change the line:

Integer.parseInt(inputSalary);

to:

convertedSalary = Integer.parseInt(inputSalary);

to do that.

Your problem is that when you are writing your numbers, these values are being written as binary numbers not as text numbers. You can fix this by doing writer.write("" + myNumber);

Integer.parseInt(inputSalary) //returns an integer

Quoting from the 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 '-' ('\-') to indicate a negative value or an ASCII plus sign '+' ('\+') 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."

Your code should read:

convertedInt = Integer.parseInt(inputSalary);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM