私はテキストファイルからの読み込みの基礎を学んでいます。私はすべてがメインメソッドにある場合、うまく動作するコードを持っています。しかし、この演習では、オープンメソッドとクローズメソッドを別々のメソッドに入れるように求められています。 openメソッドは1つの引数(ファイル名)をとり、closeメソッドは引数をとりません。ファイルのオープンとクローズ - 別個のメソッド
openメソッドは正常に動作します。近い方法は私の問題です。
import java.io.*;
class EmpInFile
{
public static void main(String[] args) throws IOException {
EmpInFile myFile = new EmpInFile() ;
myFile.openFile("payslip.txt") ;
myFile.closeFile() ;
} // end main
public void openFile(String filename) throws IOException {
String line ;
int numLines ;
// open input file
FileReader reader = new FileReader(filename) ;
BufferedReader in = new BufferedReader(reader) ;
numLines = 0 ;
// read each line from the file
line = in.readLine() ; // read first
while (line != null)
{
numLines++ ;
System.out.println(line) ; // print current
line = in.readLine() ; // read next line
}
System.out.println(numLines + "lines read from file") ;
} // end openFile
public void closeFile() throws IOException {
in.close() ;
System.out.println("file closed") ;
} // end closeFile
} // end class
彼はオープンメソッドで何かを設定しています。ローカル変数です。それを渡す必要はありません。 – duffymo
こんにちはマーティン、ありがとうございました。今はうまくいっています!あなたの助けをもう一度ありがとう! – raoulbia