Formatter类在每次写入文本文件后不会保留数据。

huangapple go评论101阅读模式
英文:

Formatter class doesn't keep data after each time writing on the text file

问题

public class IoWrite
{
    private static Formatter output; // 用于向文件输出文本的工具

    public static void main(String[] args)
    {
        openFile();
        addRecords();
        closeFile();
    }

    // 打开文件 clients.txt
    public static void openFile()
    {
        try
        {
            output = new Formatter("clients.txt"); // 打开文件
        }
        catch (SecurityException securityException)
        {
            System.err.println("写入权限被拒绝。终止程序。");
            System.exit(1); // 终止程序
        }
        catch (FileNotFoundException fileNotFoundException)
        {
            System.err.println("文件打开错误。终止程序。");
            System.exit(1); // 终止程序
        }
    }

    // 向文件添加记录
    public static void addRecords()
    {
        Scanner input = new Scanner(System.in);
        System.out.printf("%s%n%s%n? ",
                "输入账号、名字、姓氏和余额。",
                "输入文件结束指示符以结束输入。");

        while (input.hasNext()) // 循环直到文件结束指示符
        {
            try
            {
                // 将新记录输出到文件;假定输入有效
                output.format("%d %s %s %.2f%n", input.nextInt(),
                        input.next(), input.next(), input.nextDouble());
            }
            catch (FormatterClosedException formatterClosedException)
            {
                System.err.println("写入文件出错。终止程序。");
                break;
            }
            catch (NoSuchElementException elementException)
            {
                System.err.println("无效的输入。请重试。");
                input.nextLine(); // 丢弃输入,以便用户重试
            }

            System.out.print("?");
        }
    }

    // 关闭文件
    public static void closeFile()
    {
        if (output != null)
            output.close();
    }
} // end class CreateTextFile
英文:

I am developing a application that write on the text file. application write the data on the file correctly but if I restart the application and write new input it replace the new input to the old one that I write on file perversely, but what i need it is to keep the old input that i wrote before with the new one

public class IoWrite
{
private static Formatter output; // outputs text to a file
public static void main(String[] args)
{
openFile();
addRecords();
closeFile();
}
// open file clients.txt
public static void openFile()
{
try
{
output = new Formatter("clients.txt"); // open the file
}
catch (SecurityException securityException)
{
System.err.println("Write permission denied. Terminating.");
System.exit(1); // terminate the program
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening file. Terminating.");
System.exit(1); // terminate the program
}
}
// add records to file
public static void addRecords()
{
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n? ",
"Enter account number, first name, last name and balance.",
"Enter end-of-file indicator to end input.");
while (input.hasNext()) // loop until end-of-file indicator
{
try
{
// output new record to file; assumes valid input
output.format("%d %s %s %.2f%n", input.nextInt(),
input.next(), input.next(), input.nextDouble());
}
catch (FormatterClosedException formatterClosedException)
{
System.err.println("Error writing to file. Terminating.");
break;
}
catch (NoSuchElementException elementException)
{
System.err.println("Invalid input. Please try again.");
input.nextLine(); // discard input so user can try again
}
System.out.print("?");
}
}
// close file
public static void closeFile()
{
if (output != null)
output.close();
}
} // end class CreateTextFile

答案1

得分: 0

你可以使用[FileWriter][1]来追加到现有文件。

openFile方法更新为:

// 打开文件 clients.txt
public static void openFile()
{
    try
    {
        FileWriter fileWriter = new FileWriter("clients.txt", true);
        output = new Formatter(fileWriter); // 打开文件
    }
    catch (SecurityException securityException)
    {
        System.err.println("写入权限被拒绝。终止程序。");
        System.exit(1); // 终止程序
    }
    catch (FileNotFoundException fileNotFoundException)
    {
        System.err.println("打开文件时出错。终止程序。");
        System.exit(1); // 终止程序
    }
}

注意`FileWriter`构造函数中我将`append`标志设置为true

  [1]: https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html


<details>
<summary>英文:</summary>

You can use a [FileWriter][1] to append to existing file.

Update `openFile` method as,

    // open file clients.txt
    public static void openFile()
    {
        try
        {
            FileWriter fileWriter = new FileWriter(&quot;clients.txt&quot;, true);
            output = new Formatter(fileWriter); // open the file
        }
        catch (SecurityException securityException)
        {
            System.err.println(&quot;Write permission denied. Terminating.&quot;);
            System.exit(1); // terminate the program
        }
        catch (FileNotFoundException fileNotFoundException)
        {
            System.err.println(&quot;Error opening file. Terminating.&quot;);
            System.exit(1); // terminate the program
        }
    }

Note- In `FileWriter` constructor I have kept `append` flag as true

  [1]: https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html

</details>



huangapple
  • 本文由 发表于 2020年9月22日 18:37:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/64007985.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定