如何查看由 Formatter Class 创建的文件的输出

How to see an output of a file that has been created by Formatter Class

我写了下面的代码,它创建了一个文件并完美地写入了它,但是我想在输出中看到文件的内容,但我只收到这条消息:"java.io.BufferedWriter@140e19d"。 我不明白!任何人都可以向我解释为什么我收到这条消息吗?以及我应该怎么做才能看到文件的内容? tnx.

这是我的代码:

package com.example.idea;

import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;

public class Main {

 public static void main(String[] args) {

    Formatter file = null;
    Scanner sc =null;
    try {
        file = new Formatter("D:\test.txt");
        file.format("%s %s", "Hello", "World");
        sc = new Scanner(String.valueOf(file));
        while (sc.hasNext()){
            System.out.println(sc.next());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }finally {
        if (file != null) {
            file.close();
        }
        if (sc != null) {
            sc.close();
        }
    }




    }

}

使用以下内容:

sc = new Scanner(file);

使代码正常工作所需的最小更改是替换行

sc = new Scanner(String.valueOf(file));    // WRONG!!!

file.close();
sc = new Scanner(new FileInputStream("D:\test.txt"));

毫无疑问,您希望 String.valueOf(file) 以某种方式让您访问文件 D:\test.txt 内容 ,这样 Scanner 然后可以读取这些内容。 一个Formatter写入数据;它无法读回数据。为此,您需要 FileInputStream.

所以,首先,通过关闭 Formatter:

来完成对文件的写入
file.close();

现在 D:\test.txt 和其他任何文件一样只是磁盘上的一个文件,现在可以用 FileInputStream:

打开阅读
new FileInputStream("D:\test.txt")

如果愿意,您可以将该流包装在 Scanner:

sc = new Scanner(new FileInputStream("D:\test.txt"));

然后调用 Scanner 方法处理数据。

这是您的示例的更彻底修改版本,更清楚地突出了写入和读取操作之间的分离:

public class Main
{
    private static void writeFile(String fileName) throws FileNotFoundException
    {
        Formatter file = null;
        try {
            file = new Formatter(fileName);
            file.format("%s %s", "Hello", "World");
        } finally {
            if (file != null) {
                file.close();
            }
        }
    }

    private static void readFile(String fileName) throws FileNotFoundException
    {
        Scanner sc = null;
        try {
            sc = new Scanner(new FileInputStream(fileName));
            while (sc.hasNext()) {
                System.out.println(sc.next());
            }
        } finally {
            if (sc != null) {
                sc.close();
            }
        }
    }

    public static void main(String[] args)
    {
        final String fileName = "test.txt";
        try {
            writeFile(fileName);
            readFile(fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}