Java 打开和关闭文件-单独的方法
我正在学习阅读文本文件的基础知识。如果一切都在main方法中,我的代码就可以正常工作。但是,在这个练习中,我被要求将open和close方法放在不同的方法中。open方法只接受一个参数filename,close方法不接受任何参数 开放式方法工作得很好。封闭方法是我的问题Java 打开和关闭文件-单独的方法,java,file,methods,Java,File,Methods,我正在学习阅读文本文件的基础知识。如果一切都在main方法中,我的代码就可以正常工作。但是,在这个练习中,我被要求将open和close方法放在不同的方法中。open方法只接受一个参数filename,close方法不接受任何参数 开放式方法工作得很好。封闭方法是我的问题 import java.io.*; class EmpInFile { public static void main(String[] args) throws IOException { EmpI
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
您需要在类级别字段中进行修改。我认为这是一个糟糕的设计。您的openFile方法所做的远不止这些——它读取完整的内容并将它们回送到控制台,但这就是您所做的 我看不出你的封闭方法有什么价值。你最好传入一个文件以关闭。当您简单地从java.io.File包装方法时,您做了什么?至少要处理异常,这样用户就不必这样做了 我不建议使用类变量。您可以编写三种更有用的静态方法:
package utils;
public class FileUtils
{
public static Reader openFile(String fileName) throws IOException
{
return new FileReader(new File(fileName));
}
public static List<String> readFile(String fileName) throws IOException
{
List<String> contents = new ArrayList<String>();
BufferedReader br = null;
try
{
br = new BufferedReader(openFile(fileName));
while ((String line = br.readLine()) != null)
{
contents.add(line);
}
}
finally
{
close(br);
}
return contents;
}
public static void close(Reader r)
{
try
{
if (r != null)
{
r.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
您的文件指针在close方法中不可见。要使用open和close方法,您的FileReader必须是成员变量。要让openFile和closeFile共享一些数据,您需要将这些数据作为字段放入类中
import java.io.*;
class EmpInFile
{
// shared data here.
BufferedReader in;
public void openFile() {
... set something in "in"
}
public void closeFile() {
... close "in"
}
我只想在这里补充一点。这不是一个答案,而是对你有用的信息。您不需要同时关闭BuffuredReader和FileReader。关闭BufferedReader中的任意一个就足够了。前面的问题已经回答了你应该知道如何在课堂上做到这一点。他在开放式方法中设置了一些东西-这是一个局部变量,不需要传入。嗨,马丁,非常感谢。它现在工作得很好!再次感谢你的帮助!虽然我完全同意,但我相信你的回答对初学者来说没有什么价值。对一个不喜欢这个话题的人来说太神秘了。