java - 如何在 .txt 文件上写入内容?

标签 java file oop

我是 java 新手,正在开发一个程序,该程序计算以 10 为基数的二进制数,并将每个有效条目保存在 .txt 文件中。问题是每个条目都被覆盖,唯一保存的是最后输入的条目。谁能指出我做错了什么?以及有关改进语法的任何提示。非常感谢。

import java.util.Scanner;
import java.io.*;

public class BinaryNum {
    public static void main(String[] args) throws IOException //for file writing
    {
        Scanner keyboard = new Scanner(System.in);
        String userEntry;// initial input by user for binary numbers

        int ValidUserEntryNum;
        int Decimal;
        boolean decision = false; //bool to let user choose to continue
        boolean bool; //variable to check if the valid string is a binary number

        //loops for when the user names a choice
        while(!decision)
        {
            //loops for when the user enters a binary number
            do {
                System.out.println("Please Enter a Binary Number: ");
                userEntry = keyboard.nextLine();

                //check to see if input is a string of numbers
                userEntry = checkEntry (userEntry);

                // convert string to int
                ValidUserEntryNum = Integer.parseInt(userEntry);

                //bool variable to see if the number is Binary
                bool = CheckIsBinary (ValidUserEntryNum);

                //check to see if the number is binary
                if (!bool)
                {
                    System.out.println("** Invalid.Input Must be a Binary number **");
                }
            } while(bool == false); //parameter for the loop (whether the number entered was binary)

            //convert binary number to decimal number
            Decimal = convert(ValidUserEntryNum);

            //display on console
            System.out.println("You Entered: " + ValidUserEntryNum);
            System.out.println("It's base 10 equivilant is: " + Decimal);
            System.out.println();

            //creates the file name
            File fileWR = new File("outDataFile.txt");
            //creates the file object
            fileWR.createNewFile();

            BufferedWriter output = new BufferedWriter(new FileWriter(fileWR));

            //to check if there is an existing file
            if (fileWR.exists())
            {
                //writes in the file
                output.write("You Entered: " + ValidUserEntryNum +"\r\n");
                output.write("It's base 10 equivilant is " + Decimal +"\r\n");
                output.close();
            }
            else //creates a new file if one doesnt already exist.
            {
                fileWR.createNewFile();
            }

            //option if the user wants to continue
            System.out.println("Do you wish to continue?(yes or no):");
            String st = keyboard.nextLine();
            if (st.contentEquals("no"))
            {
                decision = true;
            }
        }

    }
    //to check if the user entered only a string of numbers (done)
    public static String checkEntry (String userAnswer)
    {
        int UserLength = userAnswer.length();
        int counter = 0;//to iterate through the string
        // Create a Scanner object to read input.
        Scanner keyboard = new Scanner(System.in);

        while (UserLength == 0)
        {
            System.out.println("That is a blank");
            System.out.println("Try again");
            userAnswer = null;
            userAnswer = keyboard.nextLine();
            UserLength = userAnswer.length();
        }

        while (counter < UserLength)
        {
            if (!Character.isDigit(userAnswer.charAt(counter)))
            {
                System.out.println("That is not a binary number");
                System.out.println("Try again");
                userAnswer = null;
                userAnswer = keyboard.nextLine();
                UserLength = userAnswer.length();
                counter = 0;
            }
            else
            {
                counter++;
            }
            while (UserLength == 0)
            {
                System.out.println("That is a blank, again");
                System.out.println("Try again");
                userAnswer = null;
                userAnswer = keyboard.nextLine();
                UserLength = userAnswer.length();
            }
        }
        return userAnswer;
    }

    //method to check if the entered number is binary. (done)
    public static boolean CheckIsBinary (int TrueBinary)
    {
        int temp;

        while (TrueBinary > 0)
        {
            temp = (TrueBinary % 10);
            if (temp != 1 && temp != 0)
            {
                return false;
            }
            TrueBinary = (TrueBinary/10);
        }
        return true;
    }

    //converts user binary to decimal
    public static int convert(int ValidUserEntryNum)
    {
        //creating variables to convert binary to decimals
        int temp = 0;
        int Decimal = 0;
        int power = 0;

        //Convert the binary number to a decimal number
        while (ValidUserEntryNum != 0)
        {
            temp = (ValidUserEntryNum % 10);
            Decimal += temp * Math.pow(2, power++);
            ValidUserEntryNum = (ValidUserEntryNum/10);
        } return Decimal;
    }

}

最佳答案

您每次在循环内都会创建一个新的FileWriter 和一个新的BufferedWriter,这是不必要的。您可以将其移到循环之外。

要使现有代码正常工作,请进行更改

new FileWriter(fileWR)

new FileWriter(fileWR, true)

传递的第二个参数是append标志。来自 javadocs(强调我的)

boolean if true, then data will be written to the end of the file rather than the beginning.

关于java - 如何在 .txt 文件上写入内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58254118/

相关文章:

python - 加载和解析具有多个 JSON 对象的 JSON 文件

javascript - 为什么我必须在 OOP Javascript 中使用 constructor.prototype?

javascript - 如何在不单独列出它们的情况下为 javascript 中的所有事件添加事件监听器?

java - 我如何找到导致内存泄漏的应用程序

ios - Swift 将 UITextView 的文本保存在带有属性的文件中

java - Google App Engine JDO 问题

c++ - fopen() 在内部更改我的文件名?

java - 将组合框和JLabel数组、图片绑定(bind)在一起

java - 边唱歌边连续语音识别?

java - 如何在数组中获取动态微调器选择的项目 ID?