gpt4 book ai didi

java - 如何制作一个接受文件名并可以打印其内容的类?

转载 作者:搜寻专家 更新时间:2023-10-31 20:17:31 29 4
gpt4 key购买 nike

我在创建一个可以从文件中读取和打印的类时遇到了问题。似乎传递给构造函数的文件名实际上并未分配给 fileName 变量,或者我对 File 和 Scanner 对象做错了什么。我真的不知道出了什么问题或如何解决它。我是初学者,刚刚在类里面使用文件,所以我可能遗漏了一些明显的东西。感谢任何人都可以提供的帮助:)

这是我的所有代码和下面作业的说明。

任务是:

Write a class named FileDisplay with the following methods:

  • constructor: accepts file name as argument

  • displayHead: This method should display only the first five lines of the file’s contents. If the file contains less than five lines, it should display the file’s entire contents.

  • displayContents: This method should display the entire contents of the file, the name of which was passed to the constructor.

  • displayWithLineNumbers: This method should display the contents of the file, the name of which was passed to the constructor. Each line should be preceded with a line number followed by a colon. The line numbering should start at 1.

我的代码:

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

public class FileDisplay {

// just using little random .txt files to test it
private String fileName = "example1.txt";

public FileDisplay(String fileName) throws IOException {
this.fileName = fileName;
}

File file = new File(fileName);
Scanner inputFile = new Scanner(file);

// displays first 5 lines of file
public void displayHead() {
for (int x = 0; x < 5 && inputFile.hasNext(); x++) {
System.out.println(" " + inputFile.nextLine());
}
}

//displays whole file
public void displayContents() {
while (inputFile.hasNext()) {
System.out.println(" " + inputFile.nextLine());
}
}

// displays whole file with line numbers
public void displayWithLineNumbers() {
while (inputFile.hasNext()) {
int x = 1;
System.out.println(x + ": " + inputFile.nextLine());
x++;
}
}

@Override
public String toString() {
return "FileDisplay [someFile=" + fileName + "]";
}

}

我还编写了一个驱动程序应用程序来测试该类是否正常工作:

import java.io.*;

public class FileDisplayTest {

public static void main(String[] args) throws IOException {

PrintWriter ex1 = new PrintWriter("example1.txt");
ex1.println("apple");
ex1.println("pear");
ex1.println("grape");
ex1.close();

FileDisplay test = new FileDisplay("example1.txt");
test.displayContents();
System.out.println(test.toString());
}
}

最佳答案

你的问题在这里:

File file = new File(fileName);

该语句在构造函数的外部

它在构造函数启动之前执行。因此文件对象是用错误的(您的默认!)名称创建的! (有关进一步阅读,请参阅 here)

这里更好的方法是:让你的字段final,并使用“constructor telescoping”;像这样:

private final String fileName;
private final Scanner scanner;

public FileDisplay() {
this("default.txt");
}

public FileDisplay(String fileName) {
this.fileName = fileName;
this.scanner = new Scanner(new File(fileName));
}

现在,编译器帮助确保您的字段按照您在构造函数中设置一次的顺序恰好初始化一次。你的技能有机会使用一些“默认”文件名创建一个 FileDisplay 对象(实际上:我建议不要这样做)。

关于java - 如何制作一个接受文件名并可以打印其内容的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42909455/

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