如果重新实例化,我应该多次关闭 FileInputStream

Should I close the FileInputStream multiple times if reinstantiate it

代码如下。我只调用一次 close 就做对了吗?

public class SeatTest extends TestCase {
    FileInputStream inputStream;
    ArrayList<File> fileNames = new ArrayList<>();

    @SuppressWarnings("unchecked")
    @Override
    protected void setUp() throws Exception {
        File dir = new File("./data/test/seat_layouts");
        fileNames = new ArrayList<File>(Arrays.asList(dir.listFiles()));
    }

    @Test
    public void testParse() throws IOException {
        for (File file : fileNames) {
            inputStream = new FileInputStream(file);
            String everyThing = IOUtils.toString(inputStream, "UTF-8");
            //do something
        }
    }

    @Override
    protected void tearDown() throws Exception {
        if (inputStream != null) {
            inputStream.close();
        }
    }


}

Should I close the FileInputStream multiple times if reinstantiate it.

是的....有点。

FileInputStream 的每个实例都应该关闭,否则您有泄漏文件描述符的风险。每次 "reinstantiate" 对象时,都会创建一个新实例,每个实例都应关闭。

例如

@Test
public void testParse() throws IOException {
    for (File file : fileNames) {
        try (FileInputStream inputStream = new FileInputStream(file)) {
            String everyThing = IOUtils.toString(inputStream, "UTF-8");
            //do something
        }
    }
}

请注意 try-with-resource 将自动关闭资源(即 inputStream)。

如果您这样做,则不需要拆解代码。