java - OOP 文件读取问题

标签 java file oop io

我在使用 OOP 读取 java 中的第一行数据时遇到一些问题。这里无需 OOP 即可工作:

    Scanner in = new Scanner(System.in); // sets up scanner
    System.out.print("Enter file name: "); //user provides file name and location
    String userFile = in.nextLine(); // accepts input from user
    File file = new File(userFile); //uses the file method to import the data
    Scanner inputFile = new Scanner(file); // uses scanner to read the data
    String fileContents = inputFile.nextLine();
    System.out.print(fileContents);

但是我无法让它在类文件中工作,因为方法 nextLine() 对于 String 类型是未定义的,即使我实际上只是在上面使用了它。

    public String Out(String userIn)
{
    String nOfStudentsIndex = userIn.nextLine();

另外为什么我不能以这种方式将文件传递给另一个类文件?

    Scanner in = new Scanner(System.in); // sets up scanner
    System.out.print("Enter file name: "); //user provides file name and location
    String userFile = in.nextLine(); // accepts input from user
    File file = new File(userFile); //uses the file method to import the data
    Scanner inputFile = new Scanner(file); // uses scanner to read the data
    System.out.println(inputFile.Out());

最佳答案

为什么不在需要的地方传入 Scanner 对象呢?例如,

// pass in Scanner, not String
public String Out(Scanner userIn) {
    String nOfStudentsIndex = userIn.nextLine();

请确保不要关闭使用 System.in 的扫描程序,直到您的程序明确使用它为止。

另外,这行不通:

Scanner inputFile = new Scanner(file); // uses scanner to read the data
System.out.println(inputFile.Out());

as Scanner 没有 Out() 方法。根据 Scanner API,您只能使用该类可用的方法。

您可以使用扫描仪解析文件,并使用 while 循环打印出每一行

Scanner fileScan = new Scanner(file); // uses scanner to read the data
while (fileScan.hasNextLine()) {
    System.out.println(fileScan.nextLine();
}
fileScan.close();

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

相关文章:

java - 有没有办法在 java 中执行 "andand"技术?

java - 单元测试 Java switch - 案例逻辑 - 多个单独的函数或多次调用

java - 绑定(bind) POJO 数组作为请求参数

c - C中文件操作中的段错误

c++ - 什么时候在 OOP 中使用友元是谨慎的?

java - Eclipse AutoValue 类无法构建

PYTHON多次从引用文件打印

Java:如何 "trim"字节数组?

Java封装概念不是很清楚

java - 无法使用对象访问父类(super class)中的字段