我写下面的代码&它创建了一个文件&写得很完美,但我希望在输出中看到文件的内容,但我只收到这条消息:“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();
}
}
}
}
答案 0 :(得分:1)
让代码正常工作所需的最小更改是替换
行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();
}
}
}
答案 1 :(得分:0)
使用以下内容:
sc = new Scanner(file);