gpt4 book ai didi

Java 1.4.2 - 读取文件

转载 作者:行者123 更新时间:2023-12-01 23:39:45 25 4
gpt4 key购买 nike

我正在尝试读取一个简单的文件,然后读取一个用户应该选择的文件。但我不断收到以下错误:

Readzilla.java:37: cannot find symbol

symbol : method FileReader(java.lang.String)

location: class java.io.BufferedReader

line = read.FileReader(newDoc);

这是代码。

import java.io.*;

public class Readzilla
{
public static void main(String[] args) throws IOException
{
String line;
BufferedReader read;
// BufferedReader "read" reads the file
BufferedReader in;
// BufferedReader "in" reads the input sent by the user
String loop;
// "loop" decides whether another document should be read

in = new BufferedReader(new InputStreamReader(System.in));
read = new BufferedReader(new FileReader("message.txt"));
line = read.readLine();

while(line != null)
{
System.out.println(line);
line = read.readLine();
}

// read another document
System.out.println("Would you like to read another document? (Y/N)");
loop = in.readLine();
loop = loop.toUpperCase();

if (loop == "Y")
{
do
{
System.out.println("What file (.txt) would you like to read?");
String newDoc = in.readLine();
// newDoc reads a text file of the user's choosing
line = read.FileReader(newDoc);
// ^ This line constantly gives errors
System.out.println("Reading...");
line = read.readLine();

while(line != null)
{
System.out.println(line);
line = read.readLine();
}

// read another document
System.out.println("Would you like to read another document? (Y/N)");
loop = in.readLine();
}
while (loop == "Y");
}
else
{
System.out.println("Closing Program...");
}
}
}

最佳答案

你的问题是这一行:

line = read.FileReader(newDoc);

没有名为 FileReader 的方法上课BufferedReader ,这就是编译器解释该行的方式。 FileReader 本身就是一个类,看起来您正在尝试打开一个新文件进行读取。因此,你会想说这样的话:

BufferedReader doc = new BufferedReader(new FileReader(newDoc));

之后,您想要替换

line = read.readLine();

line = doc.readLine()

因为这就是您从 BufferedReader 文档引用的文档中读取内容的方式。

此外,您在这里遇到了问题(我看到两次):

loop == "Y"

在 Java 中,== 仅是引用相等。你绝对希望这里的值(value)平等,所以说:

"Y".equals(loop);

这是一个常见的错误;在我看来,== 仅作为引用相等是一个糟糕的设计决策。

关于Java 1.4.2 - 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18148203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com