使用Scanner读取文件:为什么在使用Scanner读取java文件时出现错误?

时间:2009-04-20 04:01:50

标签: java file java.util.scanner

此示例演示如何使用Scanner逐行读取文件(它不执行写操作)我不知道为什么在尝试编译时出现错误。有人可以向我解释一下原因吗?我正在使用jcreatorLE和JDK 1.6来运行我的程序:

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

public final class File_read {

  public static void main(String... aArgs) throws FileNotFoundException {
    ReadWithScanner parser = new ReadWithScanner("C:\\Temp\\test.txt");
    parser.processLineByLine();
    log("Done.");
  }

  /**
  * @param aFileName full name of an existing, readable file.
  */
  public ReadWithScanner(String aFileName){
    fFile = new File(aFileName);  
  }

  /** Template method that calls {@link #processLine(String)}.  */
  public final void processLineByLine() throws FileNotFoundException {
    Scanner scanner = new Scanner(fFile);
    try {
      //first use a Scanner to get each line
      while ( scanner.hasNextLine() ){
        processLine( scanner.nextLine() );
      }
    }
    finally {
      //ensure the underlying stream is always closed
      scanner.close();
    }
  }

  /** 
  * Overridable method for processing lines in different ways.
  *  
  * <P>This simple default implementation expects simple name-value pairs, separated by an 
  * '=' sign. Examples of valid input : 
  * <tt>height = 167cm</tt>
  * <tt>mass =  65kg</tt>
  * <tt>disposition =  "grumpy"</tt>
  * <tt>this is the name = this is the value</tt>
  */
  protected void processLine(String aLine){
    //use a second Scanner to parse the content of each line 
    Scanner scanner = new Scanner(aLine);
    scanner.useDelimiter("=");
    if ( scanner.hasNext() ){
      String name = scanner.next();
      String value = scanner.next();
      log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim()) );
    }
    else {
      log("Empty or invalid line. Unable to process.");
    }
    //(no need for finally here, since String is source)
    scanner.close();
  }

  // PRIVATE //
  private final File fFile;

  private static void log(Object aObject){
    System.out.println(String.valueOf(aObject));
  }

  private String quote(String aText){
    String QUOTE = "'";
    return QUOTE + aText + QUOTE;
  }
} 

这是运行它的结果:

--------------------Configuration: <Default>--------------------
C:\Users\administrador\Documents\File_read.java:15: invalid method declaration; return type required
  public ReadWithScanner(String aFileName){
         ^
1 error

Process completed.

4 个答案:

答案 0 :(得分:6)

当你从here :-)中提取代码时,你重命名了类而不是构造函数。只允许构造函数没有返回类型。

我建议您重新命名该类或重命名构造函数。

我希望这不是功课。目前,您的教育工作者将有一个轻松的时间来证明抄袭。您至少需要更改变量名称和类名称,您可能还需要重新格式化它,包括更改类中方法的顺序。

如果是家庭作业的话。它不是,对吧? : - )

答案 1 :(得分:3)

你的“ReadWithScanner”构造函数需要匹配类的名称(“File_read”)

public File_read(String aFileName){
    fFile = new File(aFileName);  
}

答案 2 :(得分:1)

您的类名为File_read,您的构造函数名为ReadWithScanner。警告是您的构造函数需要与类命名相同。

答案 3 :(得分:0)

该类的名称是File_read,因此构造函数名称应该是File_read,但是您将名称作为ReadWithScanner,这就是它抱怨的原因。编译器认为它是一个方法名称,因此期望返回类型。