スキャナを使用してファイルを読む: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として名前を与えました。そのメソッドの名前を考えてコンパイラはそう戻り値の型を期待しています。

scroll top