用扫描仪读取的文件:为什么在Java中使用扫描仪进行读取文件时,我得到一个错误?

StackOverflow https://stackoverflow.com/questions/766846

  •  12-09-2019
  •  | 
  •  

此示例演示如何使用扫描器读取文件里逐行(它不执行写操作),我不知道为什么我得到一个错误,当我尝试编译。可能有人解释原因:我?我使用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.
有帮助吗?

解决方案

在抬离这里代码 :-),您重命名类,但没有构造函数。仅构造允许没有返回类型。

我建议你要么类重命名回或重命名的构造函数。

我希望这不是家庭作业。既然这样,你就教育家有一个简单的时间证明抄袭。你需要至少改变变量名称以及类名,你可能想也重新格式化了一下,包括改变类中的方法的顺序。

这就是,如果是作业。它不是,对不对? : - )

其他提示

您 “ReadWithScanner” 构造需要匹配类的名称( “FILE_READ”)

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

您类名为File_read和你的构造被命名为ReadWithScanner。该警告是你的构造需要被命名为相同的类。

之类的名字是FILE_READ,所以构造函数的名称应该是FILE_READ但你给了名字ReadWithScanner这就是为什么它的抱怨。编译器思维其的方法的名称,以便期望的返回类型。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top