Java 打开和关闭文件 - 单独的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4298337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:33:00  来源:igfitidea点击:

open and close files - separate methods

javafilemethods

提问by

I am learning the basics of reading from text files. I have code that works fine if everything is in the main method. However, for this exercise I am asked to put the open and close methods into separate methods. The open method takes one argument (the filename) and the close method takes no arguments.

我正在学习从文本文件中阅读的基础知识。如果一切都在 main 方法中,我的代码可以正常工作。然而,对于这个练习,我被要求将 open 和 close 方法放在单独的方法中。open 方法接受一个参数(文件名),close 方法不接受任何参数。

The open method works fine. The close method is my problem.

open 方法工作正常。close 方法是我的问题。

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

采纳答案by Martin Algesten

To have openFileand closeFileshare some data, you need to put that data as a field in the class.

要拥有openFilecloseFile共享一些数据,您需要将该数据作为字段放在类中。

import java.io.*;
class  EmpInFile
{
   // shared data here.
   BufferedReader in;

   public void openFile() {
     ... set something in "in"
   }

   public void closeFile() {
     ... close "in"
   }

回答by SLaks

You need to make ina class-level field.

您需要创建 in一个类级别的字段。

回答by duffymo

I think this is bad design. Your openFile() method is doing much more than that - it's reading the complete contents and echoing them to the console (useless, but that's what you're doing).

我认为这是糟糕的设计。您的 openFile() 方法所做的远不止这些 - 它正在读取完整的内容并将它们回显到控制台(无用,但这就是您正在做的)。

I don't see what value your close() method is providing. You'd better pass in a File to close. What have you done when you simply wrap the method from java.io.File? At least handle the exception so users don't have to.

我没有看到您的 close() 方法提供了什么价值。你最好传入一个 File 来关闭。当您简单地从 java.io.File 包装方法时,您做了什么?至少处理异常,这样用户就不必了。

I would not recommend using class variables. You can write three methods that are static that will be a lot more useful:

我不建议使用类变量。您可以编写三个更有用的静态方法:

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();
        }
    }
}

回答by kuriouscoder

Your file pointer is not visible in the closemethod. To have the openand closemethods, your FileReaderneeds to be a member variable.

您的文件指针在该close方法中不可见。要拥有openclose方法,您FileReader需要成为成员变量。

回答by gigadot

I just want to add something here. It is not an answet but a useful information for you. You do not need to close both BuffuredReader and FileReader. Closing either one of BufferedReader is enough. Previous question was answered here

我只是想在这里添加一些东西。这不是答案,而是对您有用的信息。您不需要同时关闭 BuffuredReader 和 FileReader。关闭 BufferedReader 之一就足够了。上一个问题已在此处回答