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

时间:2016-10-15 10:13:54

标签: java file fileinputstream

以下是代码。我通过只关闭一次来做对了吗?

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


}

1 个答案:

答案 0 :(得分:3)

  

如果重新复制它,我应该多次关闭FileInputStream。

是......等等。

应关闭FileInputStream的每个实例,否则您可能会泄漏文件描述符。每次“重新实例化”对象时,都要创建一个新实例,并且应关闭每个实例。

例如

@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)。

如果你这样做,则不需要拆卸代码。